//
//  SheetViewController.m
//  Contractor
//
//  Created by star j on 16/4/18.
//  Copyright © 2016年 star j. All rights reserved.
//

#import "SheetViewController.h"
#import "HMSegmentedControl.h"
#import "AFHTTPRequestOperationManager.h"
#import "CodeWithDES.h"
#import "NoticeViewController.h"
#import "RZViewController.h"
#import "CONST.h"
#import "JHCustomMenu.h"
#import "GdlistTableViewCell.h"
#import "SheetModel.h"
#import "MBProgressHUD.h"
#import "DetailSheetViewController.h"
#import "PasswordField.h"
#import "TZImagePickerController.h"
#import "TZImageManager.h"
#import <AssetsLibrary/AssetsLibrary.h>

@interface SheetViewController ()<TZImagePickerControllerDelegate,JHCustomMenuDelegate,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,MJRefreshBaseViewDelegate>
{
    NSInteger statusId ;
    NSInteger leftItemStatus ;
    UIButton *undoneBtn ;
    UIButton *havedoneBtn ;
    UIButton *errorBtn ;
    UITableView *sheetTableview ;
    NSMutableArray *sheetArray ;
    UIButton *statusBtn ;
    UIView *mainView ;
    UIView *alterview ;
    UIImageView *orderTimeBackView ;
    UIImageView *messageBackview ;
    PasswordField *Yzfield  ;
    UITextField *yearfield ;
    UITextField *monthfield ;
    UITextField *dayfield ;
    UIView *nullView ;
    NSString *beginTime ;
    NSString *endTime ;
    UIButton *morningBtn ;
    UIButton *afternoonBtn ;
    UIButton *nightBtn ;
    UIButton *alldayBtn ;
    NSMutableArray *_selectedPhotos ;
    NSMutableArray *_selectedAssets ;
    BOOL _isSelectOriginalPhoto ;
    MJRefreshHeaderView *_headerView;
    MJRefreshFooterView *_footerView;
    NSInteger gdID ;
    NSInteger pageNum ;
    MBProgressHUD *hud ;
    UIView *noRZView ;
    UIView *segmentView ;
}

@end

@implementation SheetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor] ;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.edgesForExtendedLayout = UIRectEdgeBottom | UIRectEdgeLeft | UIRectEdgeRight;
    sheetArray = [NSMutableArray array] ;
    statusId = 1 ;
    [self creatSheettableview] ;
    hud = [[MBProgressHUD alloc] initWithView:self.view];
  
}

- (void)viewDidAppear:(BOOL)animated
{
    gdID = 0 ;
    pageNum = 0 ;
    [sheetArray removeAllObjects] ;
    
    if (!statusId) {
        statusId = 1 ;
    }
    
    NSLog(@"statusID===========:%ld",(long)statusId) ;
    
    [self userRz] ;

}

- (void)createSheetSegment
{
    [segmentView removeFromSuperview] ;
    
    segmentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, __kScreenWidth, 51)] ;
    [self.view addSubview:segmentView] ;
    
//    statusId = 1 ;
    CGFloat length = __kScreenWidth / 3.0f ;
    undoneBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    
    undoneBtn.frame = CGRectMake(0, 0, length, 50) ;
    [undoneBtn setTitle:@"未完成工单" forState:UIControlStateNormal] ;
    if (statusId != 2 && statusId != 3) {
        [undoneBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal] ;
    }
    else{
        [undoneBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal] ;
    }
    undoneBtn.titleLabel.font = [UIFont systemFontOfSize: 14.0] ;
    undoneBtn.titleLabel.textAlignment = NSTextAlignmentCenter ;
    
    undoneBtn.backgroundColor = [UIColor clearColor] ;
    undoneBtn.layer.backgroundColor = [UIColor clearColor].CGColor ;
    [undoneBtn addTarget:self action:@selector(undone) forControlEvents:UIControlEventTouchUpInside] ;
    [segmentView addSubview:undoneBtn] ;
    
    UIImageView *line1 = [[UIImageView alloc] initWithFrame:CGRectMake(length, 10, 0.5, 30)] ;
    [line1 setImage:[UIImage imageNamed:@"password_alter_auth_code_divide_line.png"]] ;
    [segmentView addSubview:line1] ;
    
    
    havedoneBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    
    havedoneBtn.frame = CGRectMake(length, 0, length, 50) ;
    [havedoneBtn setTitle:@"完成工单" forState:UIControlStateNormal] ;
    if (statusId == 2) {
        [havedoneBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal] ;
    }
    else{
        [havedoneBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal] ;
    }
    havedoneBtn.titleLabel.font = [UIFont systemFontOfSize: 14.0] ;
    havedoneBtn.titleLabel.textAlignment = NSTextAlignmentCenter ;
    
    havedoneBtn.backgroundColor = [UIColor clearColor] ;
    havedoneBtn.layer.backgroundColor = [UIColor clearColor].CGColor ;
    [havedoneBtn addTarget:self action:@selector(havedone) forControlEvents:UIControlEventTouchUpInside] ;
    [segmentView addSubview:havedoneBtn] ;
    
    UIImageView *line2 = [[UIImageView alloc] initWithFrame:CGRectMake(length*2, 10, 0.5, 30)] ;
    [line2 setImage:[UIImage imageNamed:@"password_alter_auth_code_divide_line.png"]] ;
    [segmentView addSubview:line2] ;
    
    errorBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    
    errorBtn.frame = CGRectMake(length*2, 0, length, 50) ;
    [errorBtn setTitle:@"异常工单" forState:UIControlStateNormal] ;
    if (statusId == 3) {
        [errorBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal] ;
    }
    else{
        [errorBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal] ;
    }
    errorBtn.titleLabel.font = [UIFont systemFontOfSize: 14.0] ;
    errorBtn.titleLabel.textAlignment = NSTextAlignmentCenter ;
    
    errorBtn.backgroundColor = [UIColor clearColor] ;
    errorBtn.layer.backgroundColor = [UIColor clearColor].CGColor ;
    [errorBtn addTarget:self action:@selector(error) forControlEvents:UIControlEventTouchUpInside] ;
    [segmentView addSubview:errorBtn] ;
    
    UIImageView *line3 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 50, __kScreenWidth, 0.5)] ;
    [line3 setImage:[UIImage imageNamed:@"order_details_status_line.png"]] ;
    [segmentView addSubview:line3] ;
    
    
    NSUserDefaults *numdefaults = [NSUserDefaults standardUserDefaults] ;
    NSInteger undoneNum =  [[numdefaults valueForKey:@"1"] integerValue] ;;
    if (statusId !=2 && statusId != 3) {
        undoneNum = [[numdefaults valueForKey:[NSString stringWithFormat:@"%ld", (long)statusId]] integerValue] ;
    }
    NSInteger haveNum = [[numdefaults valueForKey:@"2"] integerValue] ;
    NSInteger errorNum = [[numdefaults valueForKey:@"3"] integerValue] ;
    
    if (undoneNum != 0) {
        [undoneBtn setTitle:[NSString stringWithFormat:@"未完成工单 %ld",(long)undoneNum] forState:UIControlStateNormal] ;
    }
    if (haveNum != 0) {
        [havedoneBtn setTitle:[NSString stringWithFormat:@"完成工单 %ld",(long)haveNum] forState:UIControlStateNormal] ;
    }
    if (errorNum != 0) {
        [errorBtn setTitle:[NSString stringWithFormat:@"异常工单 %ld",(long)errorNum] forState:UIControlStateNormal] ;
    }
    
}


#pragma mark - Navgationbar
- (void)createNavbar
{
    [self.menu dismissWithCompletion:nil];
    
    //右边buttonItem
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    btn.frame =CGRectMake(0, 0, 30, 20);
    
    [btn setBackgroundImage:[UIImage imageNamed:@"email_normal_icon.png"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(notice) forControlEvents:UIControlEventTouchUpInside] ;
    
    UIBarButtonItem *noticeItem = [[UIBarButtonItem alloc] initWithCustomView:btn] ;
    
    self.navigationItem.rightBarButtonItem = noticeItem ;

    //左边buttonItem
    UILabel *label = [[UILabel alloc] init] ;
    label.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:16.0f] ;
    label.backgroundColor = [UIColor clearColor] ;
    label.text = @"状态查看" ;
    label.textAlignment = NSTextAlignmentCenter ;
    label.textColor = [UIColor whiteColor] ;
    CGSize labelLength = [self lengthwithLabel:label withsize:16.0f] ;
    label.frame = CGRectMake(0, 0, labelLength.width, 18.0f) ;
    
    
    UIImageView *downImage = [[UIImageView alloc] initWithFrame:CGRectMake(labelLength.width, -2, 20, 20)] ;
    [downImage setImage:[UIImage imageNamed:@"title_screen_down_icon.png"]] ;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, labelLength.width+20, 20)] ;
    [view addSubview:label] ;
    [view addSubview:downImage] ;
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer
                                                     alloc] initWithTarget:self action:@selector(status)];
    tapGestureRecognizer.numberOfTapsRequired = 1;
    [view addGestureRecognizer: tapGestureRecognizer];
    
    if (leftItemStatus == 1) {
        UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:view] ;
        
        self.navigationItem.leftBarButtonItem = leftItem ;
    }
}

#pragma mark - 显示状态查看
- (void)status
{
    UILabel *label = [[UILabel alloc] init] ;
    label.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:16.0f] ;
    label.backgroundColor = [UIColor clearColor] ;
    label.text = @"状态查看" ;
    label.textAlignment = NSTextAlignmentCenter ;
    label.textColor = [UIColor whiteColor] ;
    CGSize labelLength = [self lengthwithLabel:label withsize:16.0f] ;
    label.frame = CGRectMake(0, 0, labelLength.width, 18.0f) ;
    
    
    UIImageView *downImage = [[UIImageView alloc] initWithFrame:CGRectMake(labelLength.width, -2, 20, 20)] ;
    [downImage setImage:[UIImage imageNamed:@"title_screen_up_icon.png"]] ;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, labelLength.width+20, 20)] ;
    [view addSubview:label] ;
    [view addSubview:downImage] ;
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer
                                                     alloc] initWithTarget:self action:@selector(createNavbar)];
    tapGestureRecognizer.numberOfTapsRequired = 1;
    [view addGestureRecognizer: tapGestureRecognizer];
    
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:view] ;

    self.navigationItem.leftBarButtonItem = leftItem ;
    
    [self showSchoolList] ;
    
    
}

//显示选择框
- (void)showSchoolList
{
    __weak __typeof(self) weakSelf = self;
    if (!self.menu) {
        
        NSArray *array = @[@"未上门",@"未上传图片",@"未评价",@"今天工单",@"明天工单"] ;
        self.menu = [[JHCustomMenu alloc] initWithDataArr:array origin:CGPointMake(0, 2) width:125 rowHeight:44];
        _menu.delegate = self;
        _menu.dismiss = ^() {
            weakSelf.menu = nil;
        };
        _menu.arrImgName = @[@"item_school.png", @"item_battle.png", @"item_list.png", @"item_chat.png", @"item_share.png"];
        [self.view addSubview:_menu];
    } else {
        [_menu dismissWithCompletion:^(JHCustomMenu *object) {
            weakSelf.menu = nil;
        }];
    }
}

- (CGSize)lengthwithLabel:(UILabel *)lable withsize:(CGFloat) size
{
    NSDictionary *attribute1 = @{NSFontAttributeName: [UIFont fontWithName:@"AvenirLTStd-Light" size:size]};
    CGSize DescSize = [lable.text boundingRectWithSize:CGSizeMake(MAXFLOAT, size) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute1 context:nil].size;
    return DescSize ;
}

//通知vc
- (void)notice
{
    NoticeViewController *vc = [[NoticeViewController alloc] init] ;
    self.hidesBottomBarWhenPushed = YES ;
    [self.navigationController pushViewController:vc animated:NO] ;
    self.hidesBottomBarWhenPushed = NO ;
}

//申请认证
- (void)pushRzVC
{
    RZViewController *vc = [[RZViewController alloc] init] ;
    self.hidesBottomBarWhenPushed = YES ;
    [self.navigationController pushViewController:vc animated:NO] ;
    self.hidesBottomBarWhenPushed = NO ;
}

//未完成
- (void)undone
{
    [undoneBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal] ;
    [havedoneBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal] ;
    [errorBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal] ;
    
    statusId = 1 ;
    gdID = 0 ;
    pageNum = 0 ;
    [sheetArray removeAllObjects] ;
    [self downloadData:statusId] ;
}

//完成
- (void)havedone
{
    [undoneBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal] ;
    [havedoneBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal] ;
    [errorBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal] ;
    
    statusId = 2 ;
    gdID = 0 ;
    pageNum = 0 ;
    [sheetArray removeAllObjects] ;
    [self downloadData:statusId] ;
}

//异常
- (void)error
{
    [undoneBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal] ;
    [havedoneBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal] ;
    [errorBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal] ;
    
    statusId = 3 ;
    gdID = 0 ;
    pageNum = 0 ;
    [sheetArray removeAllObjects] ;
    [self downloadData:statusId] ;
}

- (void)creatSheettableview
{
    sheetTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 52, __kScreenWidth, self.view.frame.size.height - 115)  style:UITableViewStylePlain] ;
    sheetTableview.separatorStyle = UITableViewCellSeparatorStyleNone ;
    sheetTableview.showsVerticalScrollIndicator = NO;
    sheetTableview.scrollEnabled = YES ;
    sheetTableview.delegate = self ;
    sheetTableview.dataSource = self ;
    [self.view addSubview:sheetTableview] ;
    
    _headerView = [MJRefreshHeaderView header] ;
    _headerView.scrollView = sheetTableview ;
    _headerView.delegate = self ;
    
    _footerView = [MJRefreshFooterView footer] ;
    _footerView.scrollView = sheetTableview ;
    _footerView.delegate = self ;
    
}

#pragma mark - TableviewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1 ;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //return 10 ;
     NSLog(@"********%lu********",(unsigned long)sheetArray.count) ;
    return sheetArray.count ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GdlistTableViewCell *cell = [GdlistTableViewCell cellWithTableView:tableView] ;
    cell.selectionStyle = UITableViewCellSelectionStyleNone ;
    
    SheetModel *model = [[SheetModel alloc] init] ;
    NSLog(@"=========%lu========",(unsigned long)sheetArray.count) ;
    model = sheetArray[indexPath.row] ;
    [cell.statusBtn removeFromSuperview] ;
    [self createCellbtn:model incell:cell] ;

    [cell config:sheetArray[indexPath.row]] ;
    
    return cell ;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80 ;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailSheetViewController *vc = [[DetailSheetViewController alloc] init] ;
    SheetModel *model = sheetArray[indexPath.row] ;
    vc.gdorderId = model.orderid ;
    vc.gdstatus = model.gdstatusid ;
    vc.serviceAmount = model.serviceamount ;
    self.hidesBottomBarWhenPushed = YES ;
    [self.navigationController pushViewController:vc animated:NO] ;
    self.hidesBottomBarWhenPushed = NO ;
}

#pragma mark- MJRefreshDelegate
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    if (refreshView == _headerView) {
        pageNum = 0 ;
        gdID = 0 ;
        
        [sheetArray removeAllObjects] ;
        
        [self downloadData:statusId] ;
    }
    if (refreshView == _footerView) {
        NSLog(@"GDID====%ld",(long)gdID) ;
        pageNum++ ;
       [self downloadData:statusId] ;
    }
}

//- (void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
//{
//    [refreshView endRefreshing] ;
//}

#pragma mark - 创建cell右侧按钮
- (void)createCellbtn:(SheetModel *)model incell:(GdlistTableViewCell *)cell
{
    statusBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    if ([model.gdstatusid integerValue] == 3) {
        //statusBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
        [statusBtn setTitle:@"接单" forState:UIControlStateNormal] ;
        statusBtn.frame = CGRectMake(__kScreenWidth*2/3 + 10, 15, __kScreenWidth/3 - 20, 45) ;
        statusBtn.backgroundColor = [UIColor blueColor] ;
        statusBtn.layer.cornerRadius = 5.0f ;
        
        NSString *tagStr = [NSString stringWithFormat:@"%@%@",model.gdID,model.gdstatusid] ;
        statusBtn.tag = [tagStr integerValue];
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults] ;
        [userDefault setValue:model.orderid forKey:tagStr] ;
        
        NSLog(@"model.orderid:%@",model.orderid) ;
        NSLog(@"tag:%ld",(long)statusBtn.tag) ;
        
        
        [statusBtn addTarget:self action:@selector(acceptSheet:) forControlEvents:UIControlEventTouchUpInside] ;
        
        //[cell addSubview:statusBtn] ;
        cell.statusBtn = statusBtn ;
    }
    else if ([model.gdstatusid integerValue] == 4)
    {
        //statusBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
        [statusBtn setTitle:@"预约时间" forState:UIControlStateNormal] ;
        statusBtn.frame = CGRectMake(__kScreenWidth*2/3 + 10, 15, __kScreenWidth/3 - 20, 45) ;
        statusBtn.backgroundColor = [UIColor blueColor] ;
        statusBtn.layer.cornerRadius = 5.0f ;
        
        NSString *tagStr = [NSString stringWithFormat:@"%@%@",model.gdID,model.gdstatusid] ;
        statusBtn.tag = [tagStr integerValue];
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults] ;
        [userDefault setValue:model.orderid forKey:tagStr] ;
        
        NSLog(@"model.orderid:%@",model.orderid) ;
        NSLog(@"tag:%ld",(long)statusBtn.tag) ;
        
        [statusBtn addTarget:self action:@selector(order:) forControlEvents:UIControlEventTouchUpInside] ;
        
        //[cell addSubview:statusBtn] ;
        cell.statusBtn = statusBtn ;
        
    }

    else if ([model.gdstatusid integerValue] == 5)
    {
        //statusBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
        [statusBtn setTitle:@"上门安装" forState:UIControlStateNormal] ;
        statusBtn.frame = CGRectMake(__kScreenWidth*2/3 + 10, 15, __kScreenWidth/3 - 20, 45) ;
        statusBtn.backgroundColor = [UIColor blueColor] ;
        statusBtn.layer.cornerRadius = 5.0f ;
        
        NSString *tagStr = [NSString stringWithFormat:@"%@%@",model.gdID,model.gdstatusid] ;
        statusBtn.tag = [tagStr integerValue];
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults] ;
        [userDefault setValue:model.orderid forKey:tagStr] ;
        
        [statusBtn addTarget:self action:@selector(downloadOfDoorUP:) forControlEvents:UIControlEventTouchUpInside] ;
        
        //[cell addSubview:statusBtn] ;
        cell.statusBtn = statusBtn ;

    }
    else if ([model.gdstatusid integerValue] == 6)
    {
        //statusBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
        [statusBtn setTitle:@"上门验证" forState:UIControlStateNormal] ;
        statusBtn.frame = CGRectMake(__kScreenWidth*2/3 + 10, 15, __kScreenWidth/3 - 20, 45) ;
        statusBtn.backgroundColor = [UIColor blueColor] ;
        statusBtn.layer.cornerRadius = 5.0f ;
        
        NSString *tagStr = [NSString stringWithFormat:@"%@%@",model.gdID,model.gdstatusid] ;
        statusBtn.tag = [tagStr integerValue];
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults] ;
        [userDefault setValue:model.orderid forKey:tagStr] ;
        
        NSLog(@"model.orderid:%@",model.orderid) ;
        NSLog(@"tag:%ld",(long)statusBtn.tag) ;
        
        [statusBtn addTarget:self action:@selector(doorProving:) forControlEvents:UIControlEventTouchUpInside] ;
        
        //[cell addSubview:statusBtn] ;
        cell.statusBtn = statusBtn ;
    }
    else if ([model.gdstatusid integerValue] == 7)
    {
        //statusBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
        [statusBtn setTitle:@"完工验证" forState:UIControlStateNormal] ;
        statusBtn.frame = CGRectMake(__kScreenWidth*2/3 + 10, 15, __kScreenWidth/3 - 20, 45) ;
        statusBtn.backgroundColor = [UIColor blueColor] ;
        statusBtn.layer.cornerRadius = 5.0f ;
        
        NSString *tagStr = [NSString stringWithFormat:@"%@%@",model.gdID,model.gdstatusid] ;
        statusBtn.tag = [tagStr integerValue];
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults] ;
        [userDefault setValue:model.orderid forKey:tagStr] ;
        
        NSLog(@"model.orderid:%@",model.orderid) ;
        NSLog(@"tag:%ld",(long)statusBtn.tag) ;
        
        [statusBtn addTarget:self action:@selector(haveDoneProving:) forControlEvents:UIControlEventTouchUpInside] ;
        
        //[cell addSubview:statusBtn] ;
        cell.statusBtn = statusBtn ;
    }
    else if ([model.gdstatusid integerValue] == 14)
    {
        //statusBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
        [statusBtn setTitle:@"完成工单" forState:UIControlStateNormal] ;
        statusBtn.frame = CGRectMake(__kScreenWidth*2/3 + 10, 15, __kScreenWidth/3 - 20, 45) ;
        statusBtn.backgroundColor = [UIColor blueColor] ;
        statusBtn.layer.cornerRadius = 5.0f ;
        
        NSString *tagStr = [NSString stringWithFormat:@"%@%@",model.gdID,model.gdstatusid] ;
        statusBtn.tag = [tagStr integerValue];
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults] ;
        [userDefault setValue:model.orderid forKey:tagStr] ;
        
        NSLog(@"model.orderid:%@",model.orderid) ;
        NSLog(@"tag:%ld",(long)statusBtn.tag) ;

        
        [statusBtn addTarget:self action:@selector(havesheet:) forControlEvents:UIControlEventTouchUpInside] ;
        
        //[cell addSubview:statusBtn] ;
        cell.statusBtn = statusBtn ;
    }
    else if ([model.gdstatusid integerValue] == 15)
    {
        //statusBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
        [statusBtn setTitle:@"上传图片" forState:UIControlStateNormal] ;
        statusBtn.frame = CGRectMake(__kScreenWidth*2/3 + 10, 15, __kScreenWidth/3 - 20, 45) ;
        statusBtn.backgroundColor = [UIColor blueColor] ;
        statusBtn.layer.cornerRadius = 5.0f ;
        
        NSString *tagStr = [NSString stringWithFormat:@"%@%@",model.gdID,model.gdstatusid] ;
        statusBtn.tag = [tagStr integerValue];
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults] ;
        [userDefault setValue:model.orderid forKey:tagStr] ;
        
        NSLog(@"model.orderid:%@",model.orderid) ;
        NSLog(@"tag:%ld",(long)statusBtn.tag) ;
        
        [statusBtn addTarget:self action:@selector(uploadPic:) forControlEvents:UIControlEventTouchUpInside] ;
        
        //[cell addSubview:statusBtn] ;
        cell.statusBtn = statusBtn ;
    }
    else if ([model.gdstatusid integerValue] == 20)
    {
        //statusBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
        [statusBtn setTitle:@"确认完工" forState:UIControlStateNormal] ;
        statusBtn.frame = CGRectMake(__kScreenWidth*2/3 + 10, 15, __kScreenWidth/3 - 20, 45) ;
        statusBtn.backgroundColor = [UIColor blueColor] ;
        statusBtn.layer.cornerRadius = 5.0f ;
        
        NSString *tagStr = [NSString stringWithFormat:@"%@%@",model.gdID,model.gdstatusid] ;
        statusBtn.tag = [tagStr integerValue];
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults] ;
        [userDefault setValue:model.orderid forKey:tagStr] ;
        
        NSLog(@"model.orderid:%@",model.orderid) ;
        NSLog(@"tag:%ld",(long)statusBtn.tag) ;
        
        [statusBtn addTarget:self action:@selector(downloadOfFinish:) forControlEvents:UIControlEventTouchUpInside] ;
        
        //[cell addSubview:statusBtn] ;
        cell.statusBtn = statusBtn ;
    }
//    else
//    {
//        [statusBtn removeFromSuperview] ;
//    }

}

#pragma mark - 按钮点击事件
//接单
- (void)acceptSheet:(id)senter
{
    NSLog(@"接单") ;
    mainView = [[UIView alloc] initWithFrame:[UIApplication sharedApplication].keyWindow.frame] ;
    mainView.backgroundColor = [UIColor blackColor] ;
    mainView.alpha = 0.8 ;
    [[UIApplication sharedApplication].keyWindow addSubview:mainView] ;
    alterview = [[UIView alloc] initWithFrame:CGRectMake(__kScreenWidth / 8, (__kScreenHeight *3/4 - 50) / 2, __kScreenWidth *3/4, __kScreenWidth/4+50)] ;
    alterview.backgroundColor = [UIColor whiteColor] ;
    alterview.layer.cornerRadius = 5.0f ;
    alterview.alpha = 1 ;
    [[UIApplication sharedApplication].keyWindow addSubview:alterview] ;
    
    UILabel *label = [[UILabel alloc] init] ;
    label.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:16.0f] ;
    label.backgroundColor = [UIColor clearColor] ;
    label.textAlignment = NSTextAlignmentLeft ;
    label.textColor = [UIColor grayColor] ;
    label.text = @"是否接单？" ;
    label.frame = CGRectMake(20, (alterview.frame.size.height - 60)/2, 150, 18.0f) ;
    [alterview addSubview:label] ;
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal] ;
    //cancelBtn.titleLabel.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:16.0f] ;
    [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal] ;
    [cancelBtn setBackgroundImage:[UIImage imageNamed:@"dialog_cancel_normal_btn_bg.png"] forState:UIControlStateNormal] ;
    cancelBtn.frame = CGRectMake(10, alterview.frame.size.height - 60, (alterview.frame.size.width - 40)/2, 40) ;
    [cancelBtn addTarget:self action:@selector(removeMainView) forControlEvents:UIControlEventTouchUpInside] ;
    [alterview addSubview:cancelBtn] ;
    
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    [confirmBtn setTitle:@"确认" forState:UIControlStateNormal] ;
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal] ;
    [confirmBtn setBackgroundImage:[UIImage imageNamed:@"dialog_enter_normal_btn_bg.png"] forState:UIControlStateNormal] ;
    confirmBtn.frame = CGRectMake(cancelBtn.frame.origin.x + cancelBtn.frame.size.width + 20 , alterview.frame.size.height - 60, (alterview.frame.size.width - 40)/2, 40) ;
    
    [confirmBtn setTag:[senter tag]] ;
    [confirmBtn addTarget:self action:@selector(confirmJiedan:) forControlEvents:UIControlEventTouchUpInside] ;
    [alterview addSubview:confirmBtn] ;

}
//预约
- (void)order:(id)senter
{
    NSLog(@"预约") ;
    mainView = [[UIView alloc] initWithFrame:[UIApplication sharedApplication].keyWindow.frame] ;
    mainView.backgroundColor = [UIColor blackColor] ;
    mainView.alpha = 0.8 ;
    [[UIApplication sharedApplication].keyWindow addSubview:mainView] ;
    
    orderTimeBackView = [[UIImageView alloc] init] ;
    CGFloat heith = (__kScreenWidth - 20) * 700 / 640 ;
    orderTimeBackView.frame = CGRectMake(10, (__kScreenHeight - heith) / 2, __kScreenWidth - 20, heith) ;
    [orderTimeBackView setImage:[UIImage imageNamed:@"set_service_time_dialog_bg.png"]] ;
    orderTimeBackView.userInteractionEnabled = YES ;
    [[UIApplication sharedApplication].keyWindow addSubview:orderTimeBackView] ;
    
    UIButton *closebtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    [closebtn setImage:[UIImage imageNamed:@"set_service_time_close_normal_btn.png"] forState:UIControlStateNormal] ;
    closebtn.frame = CGRectMake(6, 6, 24, 24) ;
    [closebtn addTarget:self action:@selector(removeMainView) forControlEvents:UIControlEventTouchUpInside] ;
    [orderTimeBackView addSubview:closebtn] ;
    
    UIImageView *verticalLine = [[UIImageView alloc] init] ;
    verticalLine.frame = CGRectMake(__kScreenWidth / 4, 32, 0.5, orderTimeBackView.frame.size.height - 80) ;
    [verticalLine setImage:[UIImage imageNamed:@"set_service_time_shu_divide_line"]] ;
    [orderTimeBackView addSubview:verticalLine] ;
    
    yearfield = [self createDatefield:CGRectMake(__kScreenWidth / 4 + 10, 54, 58, 34)] ;
    
//    NSDate *GMTDate = [NSDate date];//获取当前时间，日期
//    NSTimeZone *zone = [NSTimeZone systemTimeZone];
//    NSInteger interval = [zone secondsFromGMTForDate:GMTDate];
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    
    NSDateFormatter *yearFormatter = [[NSDateFormatter alloc] init];
    [yearFormatter setDateFormat:@"YYYY"];
    NSString *yearString = [yearFormatter stringFromDate:currentDate];
    yearfield.text = yearString ;
    [orderTimeBackView addSubview:yearfield] ;
    
    UIButton *jia1Button = [UIButton buttonWithType:UIButtonTypeCustom] ;
    jia1Button.frame = CGRectMake(__kScreenWidth / 4 + 9, 20, 60, 36) ;
    [jia1Button setImage:[UIImage imageNamed:@"+.png"] forState:UIControlStateNormal] ;
    jia1Button.tag = 1 ;
    
//    UILongPressGestureRecognizer *longPressGR =
//    [[UILongPressGestureRecognizer alloc] initWithTarget:self
//                                                  action:@selector(jiaBtn:)];
//    longPressGR.minimumPressDuration = 0.5 ;
//
//    [jia1Button addGestureRecognizer:longPressGR];
    
    [jia1Button addTarget:self action:@selector(jiaBtn:) forControlEvents:UIControlEventTouchUpInside] ;
    [orderTimeBackView addSubview:jia1Button] ;
    
    UIButton *jian1Button = [UIButton buttonWithType:UIButtonTypeCustom] ;
    jian1Button.frame = CGRectMake(__kScreenWidth / 4 + 9, 87, 60, 36) ;
    [jian1Button setImage:[UIImage imageNamed:@"-.png"] forState:UIControlStateNormal] ;
    jian1Button.tag =1 ;
    [jian1Button addTarget:self action:@selector(jianBtn:) forControlEvents:UIControlEventTouchUpInside] ;
    [orderTimeBackView addSubview:jian1Button] ;
    
    monthfield = [self createDatefield:CGRectMake(__kScreenWidth / 4 + 80, 54, 58, 34)] ;
    
    NSDateFormatter *monthFormatter = [[NSDateFormatter alloc] init];
    [monthFormatter setDateFormat:@"MM"];
    NSString *monthString = [monthFormatter stringFromDate:currentDate];
    monthfield.text = monthString ;
    [orderTimeBackView addSubview:monthfield] ;
    
    UIButton *jia2Button = [UIButton buttonWithType:UIButtonTypeCustom] ;
    jia2Button.frame = CGRectMake(__kScreenWidth / 4 + 79, 20, 60, 36) ;
    [jia2Button setImage:[UIImage imageNamed:@"+.png"] forState:UIControlStateNormal] ;
    jia2Button.tag = 2 ;
    [jia2Button addTarget:self action:@selector(jiaBtn:) forControlEvents:UIControlEventTouchUpInside] ;
    [orderTimeBackView addSubview:jia2Button] ;
    
    UIButton *jian2Button = [UIButton buttonWithType:UIButtonTypeCustom] ;
    jian2Button.frame = CGRectMake(__kScreenWidth / 4 + 79, 87, 60, 36) ;
    [jian2Button setImage:[UIImage imageNamed:@"-.png"] forState:UIControlStateNormal] ;
    jian2Button.tag = 2 ;
    [jian2Button addTarget:self action:@selector(jianBtn:) forControlEvents:UIControlEventTouchUpInside] ;
    [orderTimeBackView addSubview:jian2Button] ;
    
    
    dayfield = [self createDatefield:CGRectMake(__kScreenWidth / 4 + 150, 54, 45, 35)] ;
    
    NSDateFormatter *dayFormatter = [[NSDateFormatter alloc] init];
    [dayFormatter setDateFormat:@"dd"];
    NSString *dayString = [dayFormatter stringFromDate:currentDate];
    dayfield.text = dayString ;
    [orderTimeBackView addSubview:dayfield] ;
    
    UIButton *jia3Button = [UIButton buttonWithType:UIButtonTypeCustom] ;
    jia3Button.frame = CGRectMake(__kScreenWidth / 4 + 148.5, 20, 48, 36) ;
    [jia3Button setImage:[UIImage imageNamed:@"+_small.png"] forState:UIControlStateNormal] ;
    jia3Button.tag = 3 ;
    [jia3Button addTarget:self action:@selector(jiaBtn:) forControlEvents:UIControlEventTouchUpInside] ;
    [orderTimeBackView addSubview:jia3Button] ;
    
    UIButton *jian3Button = [UIButton buttonWithType:UIButtonTypeCustom] ;
    jian3Button.frame = CGRectMake(__kScreenWidth / 4 + 148.5, 87, 48, 36) ;
    [jian3Button setImage:[UIImage imageNamed:@"-_small.png"] forState:UIControlStateNormal] ;
    jian3Button.tag = 3 ;
    [jian3Button addTarget:self action:@selector(jianBtn:) forControlEvents:UIControlEventTouchUpInside] ;
    [orderTimeBackView addSubview:jian3Button] ;
    
    //选择上下午
    UIImageView *line1 = [self createline:CGRectMake(__kScreenWidth / 4 + 8, jian3Button.frame.origin.y + jian3Button.frame.size.height + 40, __kScreenWidth *3 / 4 - 36, 1)] ;
    [orderTimeBackView addSubview:line1] ;
    
    UIImageView *line2 = [self createline:CGRectMake(__kScreenWidth / 4 + 8, line1.frame.origin.y + line1.frame.size.height + 40, __kScreenWidth *3 / 4 - 36, 1)] ;
    [orderTimeBackView addSubview:line2] ;
    
    UIImageView *line3 = [self createline:CGRectMake(__kScreenWidth / 4 + 8, line2.frame.origin.y + line2.frame.size.height + 40, __kScreenWidth *3 / 4 - 36, 1)] ;
    [orderTimeBackView addSubview:line3] ;
    
    UIImageView *line4 = [self createline:CGRectMake(__kScreenWidth / 4 + 8, line3.frame.origin.y + line3.frame.size.height + 40, __kScreenWidth *3 / 4 - 36, 1)] ;
    [orderTimeBackView addSubview:line4] ;
    
    UILabel *morningLabel = [self creatlabel:14.0f color:[UIColor whiteColor] alignment:NSTextAlignmentLeft] ;
    morningLabel.frame = CGRectMake(__kScreenWidth / 4 + 8, jian3Button.frame.origin.y + jian3Button.frame.size.height + 13, 40, 16.0f) ;
    morningLabel.text = @"上午" ;
    
    UILabel *afternoonLabel = [self creatlabel:14.0f color:[UIColor whiteColor] alignment:NSTextAlignmentLeft] ;
    afternoonLabel.frame = CGRectMake(__kScreenWidth / 4 + 8, line1.frame.origin.y + line1.frame.size.height + 13, 40, 16.0f) ;
    afternoonLabel.text = @"下午" ;
    
    UILabel *nightLabel = [self creatlabel:14.0f color:[UIColor whiteColor] alignment:NSTextAlignmentLeft] ;
    nightLabel.frame = CGRectMake(__kScreenWidth / 4 + 8, line2.frame.origin.y + line2.frame.size.height + 13, 40, 16.0f) ;
    nightLabel.text = @"晚上" ;
    
    UILabel *alldayLabel = [self creatlabel:14.0f color:[UIColor whiteColor] alignment:NSTextAlignmentLeft] ;
    alldayLabel.frame = CGRectMake(__kScreenWidth / 4 + 8, line3.frame.origin.y + line3.frame.size.height + 13, 40, 16.0f) ;
    alldayLabel.text = @"全天" ;
    [orderTimeBackView addSubview:morningLabel] ;
    [orderTimeBackView addSubview:afternoonLabel] ;
    [orderTimeBackView addSubview:nightLabel] ;
    [orderTimeBackView addSubview:alldayLabel] ;
    
    UILabel *dateLabel = [self creatlabel:18.0f color:[UIColor whiteColor] alignment:NSTextAlignmentRight] ;
    dateLabel.frame = CGRectMake(__kScreenWidth / 4 - 60, 54, 50, 20.0f) ;
    dateLabel.text = @"日期" ;
    [orderTimeBackView addSubview:dateLabel] ;
    
    UILabel *timeLable = [self creatlabel:18.0f color:[UIColor whiteColor] alignment:NSTextAlignmentRight] ;
    timeLable.frame = CGRectMake(__kScreenWidth / 4 - 60, morningLabel.frame.origin.y + 20, 50, 20.0f) ;
    timeLable.text = @"时间" ;
    [orderTimeBackView addSubview:timeLable] ;
    
    
    //上午btn
    morningBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    morningBtn.frame = CGRectMake(orderTimeBackView.frame.size.width - 40, jian3Button.frame.origin.y + jian3Button.frame.size.height + 5, 30, 30) ;
    [morningBtn setBackgroundImage:[UIImage imageNamed:@"picture_list_checkbox_normal_bg"] forState:UIControlStateNormal] ;
    morningBtn.tag = 1 ;
    [morningBtn addTarget:self action:@selector(timeBtn:) forControlEvents:UIControlEventTouchUpInside] ;
    [self timeBtn:morningBtn] ;
    
    //下午btn
    afternoonBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    afternoonBtn.frame = CGRectMake(orderTimeBackView.frame.size.width - 40, line1.frame.origin.y + line1.frame.size.height + 5, 30, 30) ;
    [afternoonBtn setBackgroundImage:[UIImage imageNamed:@"picture_list_checkbox_normal_bg"] forState:UIControlStateNormal] ;
    afternoonBtn.tag = 2 ;
    [afternoonBtn addTarget:self action:@selector(timeBtn:) forControlEvents:UIControlEventTouchUpInside] ;
    
    //晚上btn
    nightBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    nightBtn.frame = CGRectMake(orderTimeBackView.frame.size.width - 40, line2.frame.origin.y + line2.frame.size.height + 5, 30, 30) ;
    [nightBtn setBackgroundImage:[UIImage imageNamed:@"picture_list_checkbox_normal_bg"] forState:UIControlStateNormal] ;
    nightBtn.tag = 3 ;
    [nightBtn addTarget:self action:@selector(timeBtn:) forControlEvents:UIControlEventTouchUpInside] ;
    
    //全天btn
    alldayBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    alldayBtn.frame = CGRectMake(orderTimeBackView.frame.size.width - 40, line3.frame.origin.y + line3.frame.size.height + 5, 30, 30) ;
    [alldayBtn setBackgroundImage:[UIImage imageNamed:@"picture_list_checkbox_normal_bg"] forState:UIControlStateNormal] ;
    alldayBtn.tag = 4 ;
    [alldayBtn addTarget:self action:@selector(timeBtn:) forControlEvents:UIControlEventTouchUpInside] ;
    
    [orderTimeBackView addSubview:morningBtn] ;
    [orderTimeBackView addSubview:afternoonBtn] ;
    [orderTimeBackView addSubview:nightBtn] ;
    [orderTimeBackView addSubview:alldayBtn] ;
    
    //取消btn
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    cancelBtn.frame = CGRectMake((orderTimeBackView.frame.size.width - 240) / 2, line4.frame.origin.y + line4.frame.size.height + 10, 100, 20) ;

    [cancelBtn setTitle:@"取消预约" forState:UIControlStateNormal] ;
    [cancelBtn addTarget:self action:@selector(removeMainView) forControlEvents:UIControlEventTouchUpInside] ;
    [orderTimeBackView addSubview:cancelBtn] ;
    
    //确认btn
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    confirmBtn.frame = CGRectMake(cancelBtn.frame.origin.x + cancelBtn.frame.size.width + 40, line4.frame.origin.y + line4.frame.size.height + 10, 100, 20) ;
    [confirmBtn setTitle:@"确认预约" forState:UIControlStateNormal] ;
    [confirmBtn setTag:[senter tag]] ;
    [confirmBtn addTarget:self action:@selector(confirmOrder:) forControlEvents:UIControlEventTouchUpInside] ;
    [orderTimeBackView addSubview:confirmBtn] ;
    
    
}

- (UIImageView *)createline:(CGRect)frame
{
    UIImageView *line = [[UIImageView alloc] initWithFrame:frame] ;
    [line setImage:[UIImage imageNamed:@"set_service_time_heng_divide_line.png"]] ;
    return line ;
}

//上门验证
- (void)doorProving:(id)sender
{
    mainView = [[UIView alloc] initWithFrame:[UIApplication sharedApplication].keyWindow.frame] ;
    mainView.backgroundColor = [UIColor blackColor] ;
    mainView.alpha = 0.8 ;
    [[UIApplication sharedApplication].keyWindow addSubview:mainView] ;
    
    CGFloat messageHeight = (__kScreenWidth - 60) * 9 / 16 ;
    messageBackview = [[UIImageView alloc] initWithFrame:CGRectMake(30, (__kScreenHeight - messageHeight) / 2, __kScreenWidth - 60, messageHeight)] ;
    [messageBackview setImage:[UIImage imageNamed:@"message_dialog_bg.png"]] ;
    messageBackview.userInteractionEnabled = YES ;
    [[UIApplication sharedApplication].keyWindow addSubview:messageBackview] ;
    UILabel *titlelabel = [[UILabel alloc] init] ;
    titlelabel.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:20.0f] ;
    titlelabel.backgroundColor = [UIColor clearColor] ;
    titlelabel.textAlignment = NSTextAlignmentLeft ;
    titlelabel.textColor = [UIColor whiteColor] ;
    titlelabel.text = @"上门验证码" ;
    titlelabel.frame = CGRectMake(10, 10, 150, 22.0f) ;
    [messageBackview addSubview:titlelabel] ;
    
    UILabel *label = [[UILabel alloc] init] ;
    label.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:16.0f] ;
    label.backgroundColor = [UIColor clearColor] ;
    label.textAlignment = NSTextAlignmentLeft ;
    label.textColor = [UIColor grayColor] ;
    label.text = @"验证码" ;
    label.frame = CGRectMake(20, (messageHeight* 3 / 4 - 50 - 16) /2 + messageHeight / 4 , 50, 18.0f) ;
    [messageBackview addSubview:label] ;
    
    Yzfield = [self createTextfield:@"输入验证码" frame:CGRectMake(80, (messageHeight* 3 / 4 - 50 - 40) /2 + messageHeight / 4 , 100, 40.0f) alignment:NSTextAlignmentLeft] ;
    [messageBackview addSubview:Yzfield] ;
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal] ;
    [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal] ;
    [cancelBtn setBackgroundImage:[UIImage imageNamed:@"dialog_cancel_normal_btn_bg.png"] forState:UIControlStateNormal] ;
    cancelBtn.frame = CGRectMake(10, messageBackview.frame.size.height - 50, (messageBackview.frame.size.width - 40)/2, 40) ;
    [cancelBtn addTarget:self action:@selector(removeMainView) forControlEvents:UIControlEventTouchUpInside] ;
    [messageBackview addSubview:cancelBtn] ;
    
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    [confirmBtn setTitle:@"确认" forState:UIControlStateNormal] ;
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal] ;
    [confirmBtn setBackgroundImage:[UIImage imageNamed:@"dialog_enter_normal_btn_bg.png"] forState:UIControlStateNormal] ;
    confirmBtn.frame = CGRectMake(cancelBtn.frame.origin.x + cancelBtn.frame.size.width + 20 , messageBackview.frame.size.height - 50, (messageBackview.frame.size.width - 40)/2, 40) ;
    [confirmBtn setTag:[sender tag]] ;
    [confirmBtn addTarget:self action:@selector(downloadOfDoorYz:) forControlEvents:UIControlEventTouchUpInside] ;
    [messageBackview addSubview:confirmBtn] ;
    
    
    NSLog(@"验证") ;
}

//完工验证
- (void)haveDoneProving:(id)sender
{
    mainView = [[UIView alloc] initWithFrame:[UIApplication sharedApplication].keyWindow.frame] ;
    mainView.backgroundColor = [UIColor blackColor] ;
    mainView.alpha = 0.8 ;
    [[UIApplication sharedApplication].keyWindow addSubview:mainView] ;
    
    CGFloat messageHeight = (__kScreenWidth - 60) * 9 / 16 ;
    messageBackview = [[UIImageView alloc] initWithFrame:CGRectMake(30, (__kScreenHeight - messageHeight) / 2, __kScreenWidth - 60, messageHeight)] ;
    [messageBackview setImage:[UIImage imageNamed:@"message_dialog_bg.png"]] ;
    messageBackview.userInteractionEnabled = YES ;
    [[UIApplication sharedApplication].keyWindow addSubview:messageBackview] ;
    UILabel *titlelabel = [[UILabel alloc] init] ;
    titlelabel.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:20.0f] ;
    titlelabel.backgroundColor = [UIColor clearColor] ;
    titlelabel.textAlignment = NSTextAlignmentLeft ;
    titlelabel.textColor = [UIColor whiteColor] ;
    titlelabel.text = @"完工验证码" ;
    titlelabel.frame = CGRectMake(10, 10, 150, 22.0f) ;
    [messageBackview addSubview:titlelabel] ;
    
    UILabel *label = [[UILabel alloc] init] ;
    label.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:16.0f] ;
    label.backgroundColor = [UIColor clearColor] ;
    label.textAlignment = NSTextAlignmentLeft ;
    label.textColor = [UIColor grayColor] ;
    label.text = @"验证码" ;
    label.frame = CGRectMake(20, (messageHeight* 3 / 4 - 50 - 16) /2 + messageHeight / 4 , 50, 18.0f) ;
    [messageBackview addSubview:label] ;
    
    Yzfield = [self createTextfield:@"输入验证码" frame:CGRectMake(80, (messageHeight* 3 / 4 - 50 - 40) /2 + messageHeight / 4 , 100, 40.0f) alignment:NSTextAlignmentLeft] ;
    [messageBackview addSubview:Yzfield] ;
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal] ;
    [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal] ;
    [cancelBtn setBackgroundImage:[UIImage imageNamed:@"dialog_cancel_normal_btn_bg.png"] forState:UIControlStateNormal] ;
    cancelBtn.frame = CGRectMake(10, messageBackview.frame.size.height - 50, (messageBackview.frame.size.width - 40)/2, 40) ;
    [cancelBtn addTarget:self action:@selector(removeMainView) forControlEvents:UIControlEventTouchUpInside] ;
    [messageBackview addSubview:cancelBtn] ;
    
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    [confirmBtn setTitle:@"确认" forState:UIControlStateNormal] ;
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal] ;
    [confirmBtn setBackgroundImage:[UIImage imageNamed:@"dialog_enter_normal_btn_bg.png"] forState:UIControlStateNormal] ;
    confirmBtn.frame = CGRectMake(cancelBtn.frame.origin.x + cancelBtn.frame.size.width + 20 , messageBackview.frame.size.height - 50, (messageBackview.frame.size.width - 40)/2, 40) ;
    [confirmBtn setTag:[sender tag]] ;
    [confirmBtn addTarget:self action:@selector(downloadOfhaveDoneYz:) forControlEvents:UIControlEventTouchUpInside] ;
    [messageBackview addSubview:confirmBtn] ;
    
    
    NSLog(@"验证") ;
}

//完成工单
- (void)havesheet:(id)sender
{
    mainView = [[UIView alloc] initWithFrame:[UIApplication sharedApplication].keyWindow.frame] ;
    mainView.backgroundColor = [UIColor blackColor] ;
    mainView.alpha = 0.8 ;
    [[UIApplication sharedApplication].keyWindow addSubview:mainView] ;
    alterview = [[UIView alloc] initWithFrame:CGRectMake(__kScreenWidth / 8, (__kScreenHeight *3/4 - 50) / 2, __kScreenWidth *3/4, __kScreenWidth/4+50)] ;
    alterview.backgroundColor = [UIColor whiteColor] ;
    alterview.layer.cornerRadius = 5.0f ;
    alterview.alpha = 1 ;
    [[UIApplication sharedApplication].keyWindow addSubview:alterview] ;
    
    UILabel *label = [[UILabel alloc] init] ;
    label.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:16.0f] ;
    label.backgroundColor = [UIColor clearColor] ;
    label.textAlignment = NSTextAlignmentLeft ;
    label.textColor = [UIColor grayColor] ;
    label.text = @"确认完成安装？" ;
    label.frame = CGRectMake(20, (alterview.frame.size.height - 60)/2, 150, 18.0f) ;
    [alterview addSubview:label] ;
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal] ;
    [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal] ;
    [cancelBtn setBackgroundImage:[UIImage imageNamed:@"dialog_cancel_normal_btn_bg.png"] forState:UIControlStateNormal] ;
    cancelBtn.frame = CGRectMake(10, alterview.frame.size.height - 60, (alterview.frame.size.width - 40)/2, 40) ;
    [cancelBtn addTarget:self action:@selector(removeMainView) forControlEvents:UIControlEventTouchUpInside] ;
    [alterview addSubview:cancelBtn] ;
    
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    [confirmBtn setTitle:@"确认" forState:UIControlStateNormal] ;
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal] ;
    [confirmBtn setBackgroundImage:[UIImage imageNamed:@"dialog_enter_normal_btn_bg.png"] forState:UIControlStateNormal] ;
    confirmBtn.frame = CGRectMake(cancelBtn.frame.origin.x + cancelBtn.frame.size.width + 20 , alterview.frame.size.height - 60, (alterview.frame.size.width - 40)/2, 40) ;
    [confirmBtn setTag:[sender tag]] ;
    [confirmBtn addTarget:self action:@selector(downloadOfHavedone:) forControlEvents:UIControlEventTouchUpInside] ;
    [alterview addSubview:confirmBtn] ;
    NSLog(@"完成") ;
}
//上传图片
- (void)uploadPic:(id)sender
{
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:3 delegate:self];
    imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
    imagePickerVc.selectedAssets = _selectedAssets; // optional, 可选的
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (photos.count > 0) {
            [_selectedAssets removeAllObjects] ;
            [self UploadPic:sender withpicArray:photos] ;
        }
        else{
            NSLog(@"图片张数不足1");
        }
    }];
    
    // Set the appearance
    // 在这里设置imagePickerVc的外观
    // imagePickerVc.navigationBar.barTintColor = [UIColor greenColor];
    // imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    // imagePickerVc.oKButtonTitleColorNormal = [UIColor greenColor];
    
    // Set allow picking video & photo & originalPhoto or not
    // 设置是否可以选择视频/图片/原图
    // imagePickerVc.allowPickingVideo = NO;
    // imagePickerVc.allowPickingImage = NO;
    // imagePickerVc.allowPickingOriginalPhoto = NO;
    
    [self presentViewController:imagePickerVc animated:NO completion:nil];
    NSLog(@"上传图片") ;
}
//确认完工
- (void)provingSheet:(id)sender
{
    NSLog(@"确认完工") ;
    
}

#pragma mark - 按钮操作
- (void)removeMainView
{
    [mainView removeFromSuperview] ;
    [alterview removeFromSuperview] ;
    [orderTimeBackView removeFromSuperview] ;
    [messageBackview removeFromSuperview] ;
}

- (void)confirmJiedan:(id)sender
{
    [self removeMainView] ;
    NSInteger orderid = [sender tag] ;
    [self downloadOfJiedan:orderid] ;
}

- (void)confirmOrder:(id)sender
{
    NSInteger orderid = [sender tag] ;
    NSString *beginStr = [NSString stringWithFormat:@"%@-%@-%@ %@",yearfield.text,monthfield.text,dayfield.text,beginTime] ;
    NSString *endStr = [NSString stringWithFormat:@"%@-%@-%@ %@",yearfield.text,monthfield.text,dayfield.text,endTime] ;
    
    NSDateFormatter *endDateFormatter = [[NSDateFormatter alloc] init];
    [endDateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
    NSDate *endGMTDate= [endDateFormatter dateFromString:endStr];
    
    NSTimeZone *endZone = [NSTimeZone systemTimeZone];
    NSInteger endInterval = [endZone secondsFromGMTForDate:endGMTDate];
    NSDate *endDate = [endGMTDate dateByAddingTimeInterval:endInterval];
    
    NSDate *GMTDate = [NSDate date];//获取当前时间，日期
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:GMTDate];
    NSDate *currentDate = [GMTDate dateByAddingTimeInterval:interval];
    
    NSComparisonResult endResult = [endDate compare:currentDate] ;
    if (endResult == -1) {
        UIButton *errorbtn = [[UIButton alloc] initWithFrame:CGRectMake((__kScreenWidth - 150)/2, __kScreenHeight - 80, 150, 40)] ;
        [errorbtn setTitle:@"当前选择的时间无效" forState:UIControlStateNormal] ;
        errorbtn.titleLabel.font = [UIFont fontWithName:@"AvenirLTStd-Medium" size:14.0f] ;
        errorbtn.layer.cornerRadius = 10 ;
        errorbtn.backgroundColor = [UIColor blackColor] ;
        errorbtn.alpha = 0.8 ;
        [[UIApplication sharedApplication].keyWindow addSubview:errorbtn] ;
        [self performSelector:@selector(clearbtn:) withObject:errorbtn afterDelay:2.0] ;
    }
    else{
        [self downloadOfOrder:orderid beginTime:beginStr endTime:endStr] ;
        [self removeMainView] ;
    }
    NSLog(@"endResult:%ld endDate:%@ currentdate:%@", (long)endResult, endDate,currentDate) ;
    
    NSLog(@"beginstr:%@========endstr:%@",beginStr,endStr) ;
}

//日期加
- (void)jiaBtn:(id)sender
{
    NSInteger btnTag = [sender tag] ;
    if (btnTag == 1) {
        NSInteger year = [yearfield.text integerValue] + 1 ;
        yearfield.text = [NSString stringWithFormat:@"%ld",(long)year] ;
        [self textFieldDidEndEditing:yearfield] ;
    }
    if (btnTag == 2) {
        NSInteger year = [monthfield.text integerValue] + 1 ;
        if (year < 10) {
            monthfield.text = [NSString stringWithFormat:@"0%ld",(long)year] ;
        }
        else
        {
        monthfield.text = [NSString stringWithFormat:@"%ld",(long)year] ;
        }
        [self textFieldDidEndEditing:monthfield] ;

    }
    if (btnTag == 3) {
        NSInteger year = [dayfield.text integerValue] + 1 ;
        if (year < 10) {
            dayfield.text = [NSString stringWithFormat:@"0%ld",(long)year] ;
        }
        else
        {
            dayfield.text = [NSString stringWithFormat:@"%ld",(long)year] ;
        }
        
        [self textFieldDidEndEditing:dayfield] ;
    }
    
}

//日期减
- (void)jianBtn:(id)sender
{
    NSInteger btnTag = [sender tag] ;
    if (btnTag == 1) {
        NSInteger year = [yearfield.text integerValue] - 1 ;
        yearfield.text = [NSString stringWithFormat:@"%ld",(long)year] ;
        [self textFieldDidEndEditing:yearfield] ;
    }
    if (btnTag == 2) {
        NSInteger year = [monthfield.text integerValue] - 1 ;
        if (year < 10) {
            monthfield.text = [NSString stringWithFormat:@"0%ld",(long)year] ;

        }
        else
        {
            monthfield.text = [NSString stringWithFormat:@"%ld",(long)year] ;
        }
        [self textFieldDidEndEditing:monthfield] ;
        
    }
    if (btnTag == 3) {
        NSInteger year = [dayfield.text integerValue] - 1 ;
        if (year < 10) {
            dayfield.text = [NSString stringWithFormat:@"0%ld",(long)year] ;
            
        }
        else
        {
            dayfield.text = [NSString stringWithFormat:@"%ld",(long)year] ;
        }

        [self textFieldDidEndEditing:dayfield] ;
    }

}

//选择时间
- (void)timeBtn:(id)sender
{
    NSInteger btnTag = [sender tag] ;
    switch (btnTag) {
        case 1:
            [morningBtn setImage:[UIImage imageNamed:@"picture_list_checkbox_press_bg.png"] forState:UIControlStateNormal] ;
            [afternoonBtn setImage:nil forState:UIControlStateNormal] ;
            [nightBtn setImage:nil forState:UIControlStateNormal] ;
            [alldayBtn setImage:nil forState:UIControlStateNormal] ;
            beginTime = @"06:00:00" ;
            endTime = @"12:00:00" ;
            break;
        case 2:
            [morningBtn setImage:nil forState:UIControlStateNormal] ;
            [afternoonBtn setImage:[UIImage imageNamed:@"picture_list_checkbox_press_bg.png"] forState:UIControlStateNormal] ;
            [nightBtn setImage:nil forState:UIControlStateNormal] ;
            [alldayBtn setImage:nil forState:UIControlStateNormal] ;
            beginTime = @"12:00:00" ;
            endTime = @"18:00:00" ;
            break;
        case 3:
            [morningBtn setImage:nil forState:UIControlStateNormal] ;
            [afternoonBtn setImage:nil forState:UIControlStateNormal] ;
            [nightBtn setImage:[UIImage imageNamed:@"picture_list_checkbox_press_bg.png"] forState:UIControlStateNormal] ;
            [alldayBtn setImage:nil forState:UIControlStateNormal] ;
            beginTime = @"18:00:00" ;
            endTime = @"23:59:59" ;
            break;
        case 4:
            [morningBtn setImage:nil forState:UIControlStateNormal] ;
            [afternoonBtn setImage:nil forState:UIControlStateNormal] ;
            [nightBtn setImage:nil forState:UIControlStateNormal] ;
            [alldayBtn setImage:[UIImage imageNamed:@"picture_list_checkbox_press_bg.png"] forState:UIControlStateNormal] ;
            beginTime = @"00:00:00" ;
            endTime = @"23:59:59" ;
            break ;
        default:
            break;
    }
    
    NSLog(@"时间：%@————%@",beginTime,endTime) ;
    
}

- (void)UploadPic:(id)sender withpicArray:(NSArray *)array
{
    if (array.count > 0) {
        [self downloadOfUploadPic:sender] ;
    }
    NSInteger orderid = [sender tag] ;
    
    NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
    NSInteger uidInt = [[uidDefaults valueForKey:@"uid"] integerValue] ;
    NSString *tag = [NSString stringWithFormat:@"%ld",(long)orderid] ;
    NSString *gdorderid = [uidDefaults valueForKey:tag] ;
    NSLog(@"gdorderid:%@",gdorderid) ;
    
    NSString *urlString = [NSString stringWithFormat:@"http://test.baogongpo.cn/index.php?s=/home/ServiceManage/uploadfilegddetailaction&gdorderid=%@&pictype=1&uid=%ld",gdorderid,(long)uidInt] ;
    NSLog(@"urlstring:%@",urlString) ;
    for (NSInteger i = 0; i < array.count; i++) {
        UIImage *image = array[i] ;
        //时间
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"] ;
        NSString *dateStr = [formatter stringFromDate:[NSDate date]] ;
        //地理位置
        NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
        NSString *address = [uidDefaults valueForKey:@"location"] ;
        NSString *cityStr = [[NSString alloc] init] ;
        NSString *liveStr = [[NSString alloc] init] ;
        for (int i = 0; i < address.length; i++) {
            NSString *temp = [address substringWithRange:NSMakeRange(i, 1)] ;
            if ([temp isEqualToString:@"市"]) {
                cityStr = [address substringToIndex:i+1] ;
                liveStr = [address substringFromIndex:i+1] ;
            }
        }
        NSLog(@"address:%@, cityStr:%@,  liveStr:%@",address,cityStr,liveStr) ;
        UIImage *textImage = [self waterImageWithText:image textLogoColor:dateStr text2:cityStr text3:liveStr];
        NSData* imgData = UIImageJPEGRepresentation(textImage, 0.7);
        [self downloadOfPicUrl:urlString withpicData:imgData] ;
    }

}

#pragma mark TZImagePickerControllerDelegate

/// User click cancel button
/// 用户点击了取消
- (void)imagePickerControllerDidCancel:(TZImagePickerController *)picker {
    // NSLog(@"cancel");
    [_selectedAssets removeAllObjects] ;
}

/// User finish picking photo，if assets are not empty, user picking original photo.
/// 用户选择好了图片，如果assets非空，则用户选择了原图。
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    _selectedPhotos = [NSMutableArray arrayWithArray:photos];
    _selectedAssets = [NSMutableArray arrayWithArray:assets];
    _isSelectOriginalPhoto = isSelectOriginalPhoto;
//    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(200, 100, 50, 50)] ;
//    [image setImage:_selectedPhotos[0]] ;
//    [self.view addSubview:image] ;
//    NSLog(@"image.Count = %d",_selectedPhotos.count) ;
    //    [[TZImageManager manager] get]
    //    _layout.itemCount = _selectedPhotos.count;
    //    [_collectionView reloadData];
    //    _collectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));
}

#pragma mark - 图片加水印
-(UIImage *)waterImageWithText:(UIImage *)img textLogoColor:(NSString *)text1 text2:(NSString *)text2 text3:(NSString *)text3{
    /////注：此为后来更改，用于显示中文。zyq,2013-5-8
    CGSize size = CGSizeMake(img.size.width, img.size.height); //设置上下文（画布）大小
    UIGraphicsBeginImageContext(size); //创建一个基于位图的上下文(context)，并将其设置为当前上下文
    
    CGContextRef contextRef = UIGraphicsGetCurrentContext(); //获取当前上下文
    
    CGContextTranslateCTM(contextRef, 0, img.size.height); //画布的高度
    CGContextScaleCTM(contextRef, 1.0, -1.0); //画布翻转
    CGContextDrawImage(contextRef, CGRectMake(0, 0, img.size.width, img.size.height), [img CGImage]); //在上下文种画当前图片
    
    CGContextTranslateCTM(contextRef, 0, img.size.height);
    CGContextScaleCTM(contextRef, 1.0, -1.0);
    UIFont *font = [UIFont boldSystemFontOfSize:26];
    
    NSDictionary *attr = @{NSFontAttributeName: font,  //设置字体
                           NSForegroundColorAttributeName : [UIColor whiteColor]   //设置字体颜色
                           };
    [text1 drawInRect:CGRectMake(10, img.size.height*2/3, img.size.width, 30) withAttributes:attr];
    [text2 drawInRect:CGRectMake(10, img.size.height*2/3+30, img.size.width, 30) withAttributes:attr] ;
    [text3 drawInRect:CGRectMake(10, img.size.height*2/3+60, __kScreenWidth, 30) withAttributes:attr] ;
    UIImage *targetimg =UIGraphicsGetImageFromCurrentImageContext(); //从当前上下文种获取图片
    UIGraphicsEndImageContext(); //移除栈顶的基于当前位图的图形上下文。
    return targetimg;
    
}

#pragma mark - 创建textfield
- (PasswordField *)createTextfield:(NSString *)title frame:(CGRect)frame alignment:(NSTextAlignment)alignment
{
    PasswordField *textfield = [[PasswordField alloc] initWithFrame:frame] ;
    textfield.placeholder = title ;
    textfield.delegate = self ;
    textfield.keyboardType = UIKeyboardTypeDefault ;
    textfield.backgroundColor=[UIColor whiteColor];
    textfield.layer.borderColor = [UIColor blackColor].CGColor ;
    textfield.layer.borderWidth = 1.0f ;
    textfield.layer.cornerRadius = 4.0f ;
    textfield.adjustsFontSizeToFitWidth=YES;//自适应宽度
    //设置UITextField的边框的风格
    textfield.borderStyle=UITextBorderStyleNone;
    textfield.textAlignment = alignment ;
    return textfield ;
}

- (UITextField *)createDatefield:(CGRect)frame
{
    UITextField *textfield = [[UITextField alloc] initWithFrame:frame] ;
    textfield.delegate = self ;
    textfield.keyboardType = UIKeyboardTypeNumbersAndPunctuation ;
    textfield.backgroundColor=[UIColor whiteColor];
//    textfield.layer.borderColor = [UIColor blackColor].CGColor ;
//    textfield.layer.borderWidth = 1.0f ;
//    textfield.layer.cornerRadius = 4.0f ;
    textfield.adjustsFontSizeToFitWidth=YES;//自适应宽度
    //设置UITextField的边框的风格
    textfield.borderStyle=UITextBorderStyleNone;
    textfield.textAlignment = NSTextAlignmentCenter ;
    return textfield ;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder] ;
    return YES ;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.2 animations:^{
        CGFloat messageHeight = (__kScreenWidth - 60) * 9 / 16 ;
        messageBackview.frame = CGRectMake(30, (__kScreenHeight - messageHeight) / 2 - 50, __kScreenWidth - 60, messageHeight) ;
    }];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.2 animations:^{
        CGFloat messageHeight = (__kScreenWidth - 60) * 9 / 16 ;
        messageBackview.frame = CGRectMake(30, (__kScreenHeight - messageHeight) / 2 , __kScreenWidth - 60, messageHeight) ;
    }];
    
    if ([textField isEqual:yearfield] || [textField isEqual:monthfield] || [textField isEqual:dayfield]) {
        NSInteger year = [yearfield.text integerValue] ;
        NSInteger month = [monthfield.text integerValue] ;
        NSInteger day = [dayfield.text integerValue] ;
        
        if (year < 1900 || year > 2100) {
            NSDate *currentDate = [NSDate date];//获取当前时间，日期
            NSDateFormatter *yearFormatter = [[NSDateFormatter alloc] init];
            [yearFormatter setDateFormat:@"YYYY"];
            NSString *yearString = [yearFormatter stringFromDate:currentDate];
            yearfield.text = yearString ;
        }
        
        if (month < 1 ) {
            monthfield.text = @"12" ;
            yearfield.text = [NSString stringWithFormat:@"%ld",year-1] ;
            [self textFieldDidEndEditing:yearfield] ;
        }
        else if (month > 12) {
            monthfield.text = @"01" ;
            yearfield.text = [NSString stringWithFormat:@"%ld",year+1] ;
            [self textFieldDidEndEditing:yearfield] ;
        }
        
        
        if ((month==1 || month==2 || month==4 || month== 6 || month == 8 || month == 9 || month == 11) && day < 1 ) {
            dayfield.text = @"31" ;
            monthfield.text = [NSString stringWithFormat:@"%ld",month-1] ;
            [self textFieldDidEndEditing:monthfield] ;
        }
        else if ((month==1 || month==3 || month==5 || month== 7 || month == 8 || month == 10 || month == 12) && day > 31 ){
            dayfield.text = @"01" ;
            monthfield.text = [NSString stringWithFormat:@"%ld",month+1] ;
            [self textFieldDidEndEditing:monthfield] ;
        }
        else if ((month==5 || month==7 || month==10 || month== 12) && day < 1){
            dayfield.text = @"30" ;
            monthfield.text = [NSString stringWithFormat:@"%ld",month-1] ;
            [self textFieldDidEndEditing:monthfield] ;
            
        }
        
        else if( (month==4 || month==6 || month==9 || month== 11)&& (day > 30) ){
            dayfield.text = @"01" ;
            monthfield.text = [NSString stringWithFormat:@"%ld",month+1] ;
            [self textFieldDidEndEditing:monthfield] ;
            
        }
        else if ((year % 400 == 0) && month == 3 && day < 1)
        {
            dayfield.text = @"29" ;
            monthfield.text = [NSString stringWithFormat:@"%ld",month-1] ;
            [self textFieldDidEndEditing:monthfield] ;
            
        }
        else if ((year % 400 == 0) && month == 2 && day > 29)
        {
            dayfield.text = @"01" ;
            monthfield.text = [NSString stringWithFormat:@"%ld",month+1] ;
            [self textFieldDidEndEditing:monthfield] ;
        }
        else if ((year % 400 != 0) && month == 3 && day < 1)
        {
            dayfield.text = @"28" ;
            monthfield.text = [NSString stringWithFormat:@"%ld",month-1] ;
            [self textFieldDidEndEditing:monthfield] ;
            
        }
        else if ((year % 400 != 0) && month == 2 && day > 28)
        {
            dayfield.text = @"01" ;
            monthfield.text = [NSString stringWithFormat:@"%ld",month+1] ;
            [self textFieldDidEndEditing:monthfield] ;
            
        }

    }
}

#pragma mark - 加载数据

- (void)downloadData:(NSInteger)status
{
    [nullView removeFromSuperview] ;
   
    hud.label.text = NSLocalizedString(@"正在努力加载...", @"HUD loading title") ;
    [hud setDimBackground:YES] ;
    [[UIApplication sharedApplication].keyWindow addSubview:hud] ;
    [hud showAnimated:YES] ;
    
    NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
    NSInteger uidInt = [[uidDefaults valueForKey:@"uid"] integerValue] ;
    
    //NSNumber *cmd = [[NSNumber alloc] initWithInt:5] ;
    NSNumber *cmd = [[NSNumber alloc] initWithInt:25] ;
    NSNumber *uid = [[NSNumber alloc] initWithInteger:uidInt] ;
    
    NSNumber *gdliststatus = [[NSNumber alloc] initWithInteger:status] ;
    NSNumber *pagenum = [[NSNumber alloc] initWithInteger:pageNum] ;
    NSNumber *rownum = [[NSNumber alloc] initWithInt:10] ;
    NSNumber *lastinfoid = [[NSNumber alloc] initWithInteger:gdID] ;
    
    
    NSDictionary *jsondic = @{@"gdliststatus":gdliststatus,
                              @"pagenum":pagenum,    //页数
                              @"rownum":rownum,    //每页显示数量
                              @"lastgdorderinfoid":lastinfoid    //上页最小 id
                              } ;
    
    NSString *jsonstr =  [CodeWithDES encodeWithDic:jsondic] ;
    NSLog(@"%@",jsondic) ;
    NSLog(@"%@",jsonstr) ;
    NSDictionary *parameters = @{@"cmd":cmd, @"uid":uid, @"jsonstr":jsonstr};
    NSLog(@"parameters:%@",parameters) ;
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:getAppJson parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         [hud hideAnimated:YES] ;
         //解密并解析json数据，将json转成字典
         NSString *decodeStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
         
         NSLog(@"decodeStr:%@",decodeStr) ;

         decodeStr = [CodeWithDES decodeWithStr:decodeStr] ;
         NSLog(@"decodeStr:%@",decodeStr) ;
         NSData *decodeData = [decodeStr dataUsingEncoding:NSUTF8StringEncoding] ;
         id result = [NSJSONSerialization JSONObjectWithData:decodeData options:NSJSONReadingMutableContainers error:nil] ;
         //获取字典中的值
         if ([result isKindOfClass:[NSDictionary class]])
         {
             NSDictionary *dic = result ;
             NSLog(@"通知:%@",dic) ;
             if ([dic[@"status"]integerValue] == 1) {
                 NSString *orderNum = dic[@"orderNum"] ;
                 
                 [self btnReloadNum:orderNum withstatus:status] ;
                 
                 [self createSheetSegment] ;
                
                 for (NSDictionary *sheetdic in dic[@"rows"]) {
                     SheetModel *model = [[SheetModel alloc] init] ;
                     [model setValuesForKeysWithDictionary:sheetdic] ;
                     model.gdID = sheetdic[@"id"] ;
                     gdID = [model.gdID integerValue] ;
                     NSString *address = model.gdserverlocate ;
                     address = [self address:address] ;
                     model.gdserverlocate = address ;
                     [sheetArray addObject:model] ;
                }
                 
                 NSLog(@"gdid:%ld",(long)gdID) ;
                 
             }
             
             if (sheetArray.count == 0) {
                 [self nullArraywithStatus:status] ;
             }
             NSLog(@"sheetarray.count=%lu",(unsigned long)sheetArray.count) ;
             [sheetTableview reloadData] ;

             [_headerView endRefreshing] ;
             [_footerView endRefreshing] ;
         }
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [hud hideAnimated:YES] ;
         NSLog(@"Error: %@", error);
     }];
}



- (void)userRz
{
//    [sheetTableview reloadData] ;
    [noRZView removeFromSuperview] ;
    NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
    NSInteger uidInt = [[uidDefaults valueForKey:@"uid"] integerValue] ;
    
    NSNumber *cmd = [[NSNumber alloc] initWithInt:304] ;
    NSNumber *uid = [[NSNumber alloc] initWithInteger:uidInt] ;
    NSDictionary *parameters = @{@"cmd":cmd,@"uid":uid};
    
//    hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    hud.label.text = NSLocalizedString(@"正在努力加载...", @"HUD loading title") ;
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:getAppJson parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
//         [hud hideAnimated:YES] ;
         //解密并解析json数据，将json转成字典
         NSString *decodeStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
         decodeStr = [CodeWithDES decodeWithStr:decodeStr] ;
         NSLog(@"rzStr:%@",decodeStr) ;
         NSData *decodeData = [decodeStr dataUsingEncoding:NSUTF8StringEncoding] ;
         id result = [NSJSONSerialization JSONObjectWithData:decodeData options:NSJSONReadingMutableContainers error:nil] ;
         //获取字典中的值
         if ([result isKindOfClass:[NSDictionary class]])
         {
             NSDictionary *dic = result ;
             // NSLog(@"dic:%@",dic) ;
             if ([dic[@"status"] integerValue] == 1)
             {
                 if ([dic[@"userrz"] integerValue] == 1) {
//                     [self creatSheettableview] ;
                     leftItemStatus = 1 ;
                     [self createNavbar] ;
                     NSLog(@"dicRZ:%@",dic) ;
                     NSLog(@"statusID2===========:%ld",(long)statusId) ;
                     [self downloadData:statusId] ;
                 }
                 else
                 {
                     leftItemStatus = 0 ;
                     [segmentView removeFromSuperview] ;
                    // [sheetTableview removeFromSuperview] ;
                     [sheetTableview reloadData] ;
                     [self createNavbar] ;
                     [self creatNoRZView] ;
                 }
             }
             
         }
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
//         [hud hideAnimated:YES] ;
         NSLog(@"Error: %@", error);
     }];
}

#pragma mark - 工单操作接口
- (void)downloadOfJiedan:(NSInteger)orderid
{
    NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
    NSInteger uidInt = [[uidDefaults valueForKey:@"uid"] integerValue] ;
    NSString *tag = [NSString stringWithFormat:@"%ld",(long)orderid] ;
    NSString *gdorderid = [uidDefaults valueForKey:tag] ;
    NSLog(@"gdorderid:%@",gdorderid) ;
    
    NSNumber *cmd = [[NSNumber alloc] initWithInt:205] ;
    NSNumber *uid = [[NSNumber alloc] initWithInteger:uidInt] ;

    
    NSNumber *accepttype = [[NSNumber alloc] initWithInt:1] ;
    
    NSDictionary *jsondic = @{@"gdorderid":gdorderid,
                              @"accepttype":accepttype,
                              @"memo":@"接单"
                              } ;
    NSLog(@"%@",jsondic) ;

    NSString *jsonstr =  [CodeWithDES encodeWithDic:jsondic] ;
    NSLog(@"%@",jsondic) ;
    NSLog(@"%@",jsonstr) ;
    NSDictionary *parameters = @{@"cmd":cmd, @"uid":uid, @"jsonstr":jsonstr};
    //    NSLog(@"%@",parameters) ;
    
    // NSDictionary *parameters = @{@"cmd":cmd, @"uid":uid};
    NSLog(@"parameters:%@",parameters) ;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:getAppJson parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         //解密并解析json数据，将json转成字典
         NSString *decodeStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
         NSLog(@"decodeStr:%@",decodeStr) ;
         
         decodeStr = [CodeWithDES decodeWithStr:decodeStr] ;
         NSLog(@"decodeStr:%@",decodeStr) ;
         NSData *decodeData = [decodeStr dataUsingEncoding:NSUTF8StringEncoding] ;
         id result = [NSJSONSerialization JSONObjectWithData:decodeData options:NSJSONReadingMutableContainers error:nil] ;
         //获取字典中的值
         if ([result isKindOfClass:[NSDictionary class]])
         {
             NSDictionary *dic = result ;
             NSLog(@"通知:%@",dic) ;
             if ([dic[@"status"]integerValue] == 1) {
                 gdID = 0 ;
                 pageNum = 0 ;
                 [sheetArray removeAllObjects] ;
                 [self downloadData:1] ;
             }
         }
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"Error: %@", error);
     }];
}

- (void)downloadOfOrder:(NSInteger)orderid beginTime:(NSString *)begintime endTime:(NSString *)endtime
{
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    hud.label.text = NSLocalizedString(@"正在努力加载...", @"HUD loading title") ;
    
    NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
    NSInteger uidInt = [[uidDefaults valueForKey:@"uid"] integerValue] ;
    NSString *tag = [NSString stringWithFormat:@"%ld",(long)orderid] ;
    NSString *gdorderid = [uidDefaults valueForKey:tag] ;
    NSLog(@"gdorderid:%@",gdorderid) ;
    
    NSNumber *cmd = [[NSNumber alloc] initWithInt:207] ;
    NSNumber *uid = [[NSNumber alloc] initWithInteger:uidInt] ;
    NSDictionary *jsondic = @{@"gdorderid":gdorderid,
                              @"gdSetServiceTimeBegin":begintime,
                              @"gdSetServiceTimeEnd":endtime,
                              @"memo":@""
                              } ;
    NSLog(@"%@",jsondic) ;
    
    NSString *jsonstr =  [CodeWithDES encodeWithDic:jsondic] ;
    NSLog(@"%@",jsondic) ;
    NSLog(@"%@",jsonstr) ;
    NSDictionary *parameters = @{@"cmd":cmd, @"uid":uid, @"jsonstr":jsonstr} ;
    NSLog(@"parameters:%@",parameters) ;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:getAppJson parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         //解密并解析json数据，将json转成字典
         NSString *decodeStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
         NSLog(@"decodeStr:%@",decodeStr) ;
         
         decodeStr = [CodeWithDES decodeWithStr:decodeStr] ;
         NSLog(@"decodeStr:%@",decodeStr) ;
         NSData *decodeData = [decodeStr dataUsingEncoding:NSUTF8StringEncoding] ;
         id result = [NSJSONSerialization JSONObjectWithData:decodeData options:NSJSONReadingMutableContainers error:nil] ;
         //获取字典中的值
         if ([result isKindOfClass:[NSDictionary class]])
         {
             NSDictionary *dic = result ;
             NSLog(@"通知:%@",dic) ;
             if ([dic[@"status"]integerValue] == 1) {
                 gdID = 0 ;
                 pageNum = 0 ;
                 [sheetArray removeAllObjects] ;
                 [self downloadData:1] ;
             }
         }
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"Error: %@", error);
     }];

}

- (void)downloadOfDoorUP:(id)sender
{
    NSInteger orderid = [sender tag] ;
    
    NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
    NSInteger uidInt = [[uidDefaults valueForKey:@"uid"] integerValue] ;
    NSString *tag = [NSString stringWithFormat:@"%ld",(long)orderid] ;
    NSString *gdorderid = [uidDefaults valueForKey:tag] ;
    NSLog(@"gdorderid:%@",gdorderid) ;
    
    NSNumber *cmd = [[NSNumber alloc] initWithInt:208] ;
    NSNumber *uid = [[NSNumber alloc] initWithInteger:uidInt] ;
    NSDictionary *jsondic = @{@"gdorderid":gdorderid,
                              @"memo":@"上门服务"
                              } ;
    NSLog(@"%@",jsondic) ;
    
    NSString *jsonstr =  [CodeWithDES encodeWithDic:jsondic] ;
    
    NSLog(@"%@",jsonstr) ;
    NSDictionary *parameters = @{@"cmd":cmd, @"uid":uid, @"jsonstr":jsonstr};
    NSLog(@"parameters:%@",parameters) ;
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:getAppJson parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         //解密并解析json数据，将json转成字典
         NSString *decodeStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
         NSLog(@"decodeStr:%@",decodeStr) ;
         
         decodeStr = [CodeWithDES decodeWithStr:decodeStr] ;
         NSLog(@"decodeStr:%@",decodeStr) ;
         NSData *decodeData = [decodeStr dataUsingEncoding:NSUTF8StringEncoding] ;
         id result = [NSJSONSerialization JSONObjectWithData:decodeData options:NSJSONReadingMutableContainers error:nil] ;
         //获取字典中的值
         if ([result isKindOfClass:[NSDictionary class]])
         {
             NSDictionary *dic = result ;
             NSLog(@"通知:%@",dic) ;
             if ([dic[@"status"]integerValue] == 1) {
                 gdID = 0 ;
                 pageNum = 0 ;
                 [sheetArray removeAllObjects] ;
                 [self downloadData:1] ;
             }
         }
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"Error: %@", error);
     }];
}

- (void)downloadOfDoorYz:(id)sender
{
    NSInteger orderid = [sender tag] ;
    
    NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
    NSInteger uidInt = [[uidDefaults valueForKey:@"uid"] integerValue] ;
    NSString *tag = [NSString stringWithFormat:@"%ld",(long)orderid] ;
    NSString *gdorderid = [uidDefaults valueForKey:tag] ;
    NSLog(@"gdorderid:%@",gdorderid) ;
    
    NSNumber *cmd = [[NSNumber alloc] initWithInt:217] ;
    NSNumber *uid = [[NSNumber alloc] initWithInteger:uidInt] ;
    NSDictionary *jsondic = @{@"gdorderid":gdorderid,
                              @"servicecode":Yzfield.text,
                              @"memo":@"上门服务"
                              } ;
    NSLog(@"%@",jsondic) ;
    
    NSString *jsonstr =  [CodeWithDES encodeWithDic:jsondic] ;
    
    NSLog(@"%@",jsonstr) ;
    NSDictionary *parameters = @{@"cmd":cmd, @"uid":uid, @"jsonstr":jsonstr};
    
    NSLog(@"parameters:%@",parameters) ;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    if (Yzfield.text.length == 0) {
        UIButton *errorbtn = [[UIButton alloc] initWithFrame:CGRectMake((__kScreenWidth - 100)/2, __kScreenHeight - 80, 100, 50)] ;
        [errorbtn setTitle:@"输入不能为空" forState:UIControlStateNormal] ;
        errorbtn.titleLabel.font = [UIFont fontWithName:@"AvenirLTStd-Medium" size:14.0f] ;
        errorbtn.layer.cornerRadius = 10 ;
        errorbtn.backgroundColor = [UIColor darkGrayColor] ;
        errorbtn.alpha = 0.5 ;
        [[UIApplication sharedApplication].keyWindow addSubview:errorbtn] ;
        [self performSelector:@selector(clearbtn:) withObject:errorbtn afterDelay:2.0] ;
    }
    else
    {
        [self removeMainView] ;
//        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//        hud.label.text = NSLocalizedString(@"正在努力加载...", @"HUD loading title") ;
        [manager POST:getAppJson parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             [hud hideAnimated:YES] ;
             //解密并解析json数据，将json转成字典
             NSString *decodeStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
             NSLog(@"decodeStr:%@",decodeStr) ;
             
             decodeStr = [CodeWithDES decodeWithStr:decodeStr] ;
             NSLog(@"decodeStr:%@",decodeStr) ;
             NSData *decodeData = [decodeStr dataUsingEncoding:NSUTF8StringEncoding] ;
             id result = [NSJSONSerialization JSONObjectWithData:decodeData options:NSJSONReadingMutableContainers error:nil] ;
             //获取字典中的值
             if ([result isKindOfClass:[NSDictionary class]])
             {
                 NSDictionary *dic = result ;
                 NSLog(@"通知:%@",dic) ;
                 if ([dic[@"status"]integerValue] == 1) {
                     gdID = 0 ;
                     pageNum = 0 ;
                     [sheetArray removeAllObjects] ;
                     [self downloadData:1] ;
                 }
                 else{
                     UIButton *errorbtn = [[UIButton alloc] initWithFrame:CGRectMake((__kScreenWidth - 100)/2, __kScreenHeight - 80, 100, 50)] ;
                     [errorbtn setTitle:@"工单操作失败" forState:UIControlStateNormal] ;
                     errorbtn.titleLabel.font = [UIFont fontWithName:@"AvenirLTStd-Medium" size:14.0f] ;
                     errorbtn.layer.cornerRadius = 10 ;
                     errorbtn.backgroundColor = [UIColor darkGrayColor] ;
                     errorbtn.alpha = 0.5 ;
                     [[UIApplication sharedApplication].keyWindow addSubview:errorbtn] ;
                     [self performSelector:@selector(clearbtn:) withObject:errorbtn afterDelay:2.0] ;
                 }
             }
         }
              failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
             [hud hideAnimated:YES] ;
             NSLog(@"Error: %@", error);
         }];

    }
}

- (void)downloadOfHavedone:(id)sender
{
    [self removeMainView] ;
    NSInteger orderid = [sender tag] ;
    
    NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
    NSInteger uidInt = [[uidDefaults valueForKey:@"uid"] integerValue] ;
    NSString *tag = [NSString stringWithFormat:@"%ld",(long)orderid] ;
    NSString *gdorderid = [uidDefaults valueForKey:tag] ;
    NSLog(@"gdorderid:%@",gdorderid) ;
    
    NSNumber *cmd = [[NSNumber alloc] initWithInt:209] ;
    NSNumber *uid = [[NSNumber alloc] initWithInteger:uidInt] ;
    NSDictionary *jsondic = @{@"gdorderid":gdorderid,
                              @"memo":@"工单完成"
                              } ;
    NSLog(@"%@",jsondic) ;
    
    NSString *jsonstr =  [CodeWithDES encodeWithDic:jsondic] ;
    
    NSLog(@"%@",jsonstr) ;
    NSDictionary *parameters = @{@"cmd":cmd, @"uid":uid, @"jsonstr":jsonstr};
    
    NSLog(@"parameters:%@",parameters) ;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    hud.label.text = NSLocalizedString(@"正在努力加载...", @"HUD loading title") ;
    [manager POST:getAppJson parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         [hud hideAnimated:YES] ;
         //解密并解析json数据，将json转成字典
         NSString *decodeStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
         NSLog(@"decodeStr:%@",decodeStr) ;
         
         decodeStr = [CodeWithDES decodeWithStr:decodeStr] ;
         NSLog(@"decodeStr:%@",decodeStr) ;
         NSData *decodeData = [decodeStr dataUsingEncoding:NSUTF8StringEncoding] ;
         id result = [NSJSONSerialization JSONObjectWithData:decodeData options:NSJSONReadingMutableContainers error:nil] ;
         //获取字典中的值
         if ([result isKindOfClass:[NSDictionary class]])
         {
             NSDictionary *dic = result ;
             NSLog(@"通知:%@",dic) ;
             if ([dic[@"status"]integerValue] == 1) {
                 gdID = 0 ;
                 pageNum = 0 ;
                 [sheetArray removeAllObjects] ;
                 [self downloadData:1] ;
             }
             else{
                 UIButton *errorbtn = [[UIButton alloc] initWithFrame:CGRectMake((__kScreenWidth - 100)/2, __kScreenHeight - 80, 100, 50)] ;
                 [errorbtn setTitle:@"工单操作失败" forState:UIControlStateNormal] ;
                 errorbtn.titleLabel.font = [UIFont fontWithName:@"AvenirLTStd-Medium" size:14.0f] ;
                 errorbtn.layer.cornerRadius = 10 ;
                 errorbtn.backgroundColor = [UIColor darkGrayColor] ;
                 errorbtn.alpha = 0.5 ;
                 [[UIApplication sharedApplication].keyWindow addSubview:errorbtn] ;
                 [self performSelector:@selector(clearbtn:) withObject:errorbtn afterDelay:2.0] ;
             }
         }
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [hud hideAnimated:YES] ;
         NSLog(@"Error: %@", error);
     }];

}

- (void)downloadOfhaveDoneYz:(id)sender
{
    NSInteger orderid = [sender tag] ;
    
    NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
    NSInteger uidInt = [[uidDefaults valueForKey:@"uid"] integerValue] ;
    NSString *tag = [NSString stringWithFormat:@"%ld",(long)orderid] ;
    NSString *gdorderid = [uidDefaults valueForKey:tag] ;
    NSLog(@"gdorderid:%@",gdorderid) ;
    
    NSNumber *cmd = [[NSNumber alloc] initWithInt:219] ;
    NSNumber *uid = [[NSNumber alloc] initWithInteger:uidInt] ;
    NSDictionary *jsondic = @{@"gdorderid":gdorderid,
                              @"servicecommentscode":Yzfield.text,
                              @"memo":@"工单完成客户评价"
                              } ;
    NSLog(@"%@",jsondic) ;
    
    NSString *jsonstr =  [CodeWithDES encodeWithDic:jsondic] ;
    
    NSLog(@"%@",jsonstr) ;
    NSDictionary *parameters = @{@"cmd":cmd, @"uid":uid, @"jsonstr":jsonstr};
    
    NSLog(@"parameters:%@",parameters) ;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    if (Yzfield.text.length == 0) {
        UIButton *errorbtn = [[UIButton alloc] initWithFrame:CGRectMake((__kScreenWidth - 100)/2, __kScreenHeight - 80, 100, 50)] ;
        [errorbtn setTitle:@"输入不能为空" forState:UIControlStateNormal] ;
        errorbtn.titleLabel.font = [UIFont fontWithName:@"AvenirLTStd-Medium" size:14.0f] ;
        errorbtn.layer.cornerRadius = 10 ;
        errorbtn.backgroundColor = [UIColor darkGrayColor] ;
        errorbtn.alpha = 0.5 ;
        [[UIApplication sharedApplication].keyWindow addSubview:errorbtn] ;
        [self performSelector:@selector(clearbtn:) withObject:errorbtn afterDelay:2.0] ;
    }
    else
    {
        [self removeMainView] ;
        [manager POST:getAppJson parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
            //解密并解析json数据，将json转成字典
             NSString *decodeStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
             NSLog(@"decodeStr:%@",decodeStr) ;
             
             decodeStr = [CodeWithDES decodeWithStr:decodeStr] ;
             NSLog(@"decodeStr:%@",decodeStr) ;
             NSData *decodeData = [decodeStr dataUsingEncoding:NSUTF8StringEncoding] ;
             id result = [NSJSONSerialization JSONObjectWithData:decodeData options:NSJSONReadingMutableContainers error:nil] ;
             //获取字典中的值
             if ([result isKindOfClass:[NSDictionary class]])
             {
                 NSDictionary *dic = result ;
                 NSLog(@"通知:%@",dic) ;
                 if ([dic[@"status"]integerValue] == 1) {
                     gdID = 0 ;
                     pageNum = 0 ;
                     [sheetArray removeAllObjects] ;
                     [self downloadData:1] ;
                 }
                 else{
                     UIButton *errorbtn = [[UIButton alloc] initWithFrame:CGRectMake((__kScreenWidth - 100)/2, __kScreenHeight - 80, 100, 50)] ;
                     [errorbtn setTitle:@"工单操作失败" forState:UIControlStateNormal] ;
                     errorbtn.titleLabel.font = [UIFont fontWithName:@"AvenirLTStd-Medium" size:14.0f] ;
                     errorbtn.layer.cornerRadius = 10 ;
                     errorbtn.backgroundColor = [UIColor darkGrayColor] ;
                     errorbtn.alpha = 0.5 ;
                     [[UIApplication sharedApplication].keyWindow addSubview:errorbtn] ;
                     [self performSelector:@selector(clearbtn:) withObject:errorbtn afterDelay:2.0] ;
                 }
             }
         }
              failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
             NSLog(@"Error: %@", error);
         }];
        
    }

}

- (void)downloadOfUploadPic:(id)sender
{
    NSInteger orderid = [sender tag] ;
    
    NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
    NSInteger uidInt = [[uidDefaults valueForKey:@"uid"] integerValue] ;
    NSString *tag = [NSString stringWithFormat:@"%ld",(long)orderid] ;
    NSString *gdorderid = [uidDefaults valueForKey:tag] ;
    NSLog(@"gdorderid:%@",gdorderid) ;
    
    NSNumber *cmd = [[NSNumber alloc] initWithInt:213] ;
    NSNumber *uid = [[NSNumber alloc] initWithInteger:uidInt] ;
    NSNumber *status = [[NSNumber alloc] initWithInteger:20] ;
    
    NSDictionary *jsondic = @{@"gdorderid":gdorderid,
                              @"gdstatus":status,
                              @"memo":@"上传图片"
                              } ;
    NSLog(@"%@",jsondic) ;
    
    NSString *jsonstr =  [CodeWithDES encodeWithDic:jsondic] ;
    
    NSLog(@"%@",jsonstr) ;
    NSDictionary *parameters = @{@"cmd":cmd, @"uid":uid, @"jsonstr":jsonstr};
    
    NSLog(@"parameters:%@",parameters) ;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    hud.label.text = NSLocalizedString(@"正在努力加载...", @"HUD loading title") ;
    [manager POST:getAppJson parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         [hud hideAnimated:YES] ;
         //解密并解析json数据，将json转成字典
         NSString *decodeStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
         NSLog(@"decodeStr:%@",decodeStr) ;
         
         decodeStr = [CodeWithDES decodeWithStr:decodeStr] ;
         NSLog(@"decodeStr:%@",decodeStr) ;
         NSData *decodeData = [decodeStr dataUsingEncoding:NSUTF8StringEncoding] ;
         id result = [NSJSONSerialization JSONObjectWithData:decodeData options:NSJSONReadingMutableContainers error:nil] ;
         //获取字典中的值
         if ([result isKindOfClass:[NSDictionary class]])
         {
             NSDictionary *dic = result ;
             NSLog(@"通知:%@",dic) ;
             if ([dic[@"status"]integerValue] == 1) {
                 
             }
             else{
                 UIButton *errorbtn = [[UIButton alloc] initWithFrame:CGRectMake((__kScreenWidth - 100)/2, __kScreenHeight - 80, 100, 50)] ;
                 [errorbtn setTitle:@"工单操作失败" forState:UIControlStateNormal] ;
                 errorbtn.titleLabel.font = [UIFont fontWithName:@"AvenirLTStd-Medium" size:14.0f] ;
                 errorbtn.layer.cornerRadius = 10 ;
                 errorbtn.backgroundColor = [UIColor darkGrayColor] ;
                 errorbtn.alpha = 0.5 ;
                 [[UIApplication sharedApplication].keyWindow addSubview:errorbtn] ;
                 [self performSelector:@selector(clearbtn:) withObject:errorbtn afterDelay:2.0] ;
             }
         }
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [hud hideAnimated:YES] ;
         NSLog(@"Error: %@", error);
     }];

}

- (void)downloadOfPicUrl:(NSString *)url withpicData:(NSData *)imageData
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    //NSLog(@"paths : %@",paths) ;
    
    
    //给照片按拍摄时间命名
    NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"images.jpg"]]; ;
    
    [imageData writeToFile: uniquePath atomically:YES];
    
   // NSData *pathdata = [NSData dataWithContentsOfFile:uniquePath] ;
    //[pathdata writeToFile:uniquePath atomically:YES] ;
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    hud.label.text = NSLocalizedString(@"正在努力加载...", @"HUD loading title") ;
    
    [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
       // [formData appendPartWithFormData:imageData name:@""] ;
       [formData appendPartWithFileData:imageData name:@"gdpic" fileName:uniquePath mimeType:@"image/jpeg"] ;
        
    } success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        NSString *decodeStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
        NSLog(@"ImagebackStr:%@",decodeStr) ;
        
        id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil] ;
        
        if ([result isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dic = result ;
            NSLog(@"图片上传成功:%@",dic) ;
            if ([dic[@"status"] integerValue] == 1) {
                
            }
        }
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"上传失败：%@",error) ;
    }] ;

}


- (void)downloadOfFinish:(id)sender
{
    [self removeMainView] ;
    NSInteger orderid = [sender tag] ;
    
    NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
    NSInteger uidInt = [[uidDefaults valueForKey:@"uid"] integerValue] ;
    NSString *tag = [NSString stringWithFormat:@"%ld",(long)orderid] ;
    NSString *gdorderid = [uidDefaults valueForKey:tag] ;
    NSLog(@"gdorderid:%@",gdorderid) ;
    
    NSNumber *cmd = [[NSNumber alloc] initWithInt:220] ;
    NSNumber *uid = [[NSNumber alloc] initWithInteger:uidInt] ;
    NSDictionary *jsondic = @{@"gdorderid":gdorderid,
                              @"memo":@"确认完工"
                              } ;
    NSLog(@"%@",jsondic) ;
    
    NSString *jsonstr =  [CodeWithDES encodeWithDic:jsondic] ;
    
    NSLog(@"%@",jsonstr) ;
    NSDictionary *parameters = @{@"cmd":cmd, @"uid":uid, @"jsonstr":jsonstr};
    
    NSLog(@"parameters:%@",parameters) ;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    hud.label.text = NSLocalizedString(@"正在努力加载...", @"HUD loading title") ;
    [manager POST:getAppJson parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         [hud hideAnimated:YES] ;
         //解密并解析json数据，将json转成字典
         NSString *decodeStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
         NSLog(@"decodeStr:%@",decodeStr) ;
         
         decodeStr = [CodeWithDES decodeWithStr:decodeStr] ;
         NSLog(@"decodeStr:%@",decodeStr) ;
         NSData *decodeData = [decodeStr dataUsingEncoding:NSUTF8StringEncoding] ;
         id result = [NSJSONSerialization JSONObjectWithData:decodeData options:NSJSONReadingMutableContainers error:nil] ;
         //获取字典中的值
         if ([result isKindOfClass:[NSDictionary class]])
         {
             NSDictionary *dic = result ;
             NSLog(@"通知:%@",dic) ;
             if ([dic[@"status"]integerValue] == 1) {
                 gdID = 0 ;
                 pageNum = 0 ;
                 [sheetArray removeAllObjects] ;
                 [self downloadData:1] ;
             }
             else{
                 UIButton *errorbtn = [[UIButton alloc] initWithFrame:CGRectMake((__kScreenWidth - 100)/2, __kScreenHeight - 80, 100, 50)] ;
                 [errorbtn setTitle:@"工单操作失败" forState:UIControlStateNormal] ;
                 errorbtn.titleLabel.font = [UIFont fontWithName:@"AvenirLTStd-Medium" size:14.0f] ;
                 errorbtn.layer.cornerRadius = 10 ;
                 errorbtn.backgroundColor = [UIColor darkGrayColor] ;
                 errorbtn.alpha = 0.5 ;
                 [[UIApplication sharedApplication].keyWindow addSubview:errorbtn] ;
                 [self performSelector:@selector(clearbtn:) withObject:errorbtn afterDelay:2.0] ;
             }
         }
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [hud hideAnimated:YES] ;
         NSLog(@"Error: %@", error);
     }];
    
}

#pragma mark - 更新按钮数字
- (void)btnReloadNum:(NSString *)num withstatus:(NSInteger) status
{
    NSUserDefaults *numdefaults = [NSUserDefaults standardUserDefaults] ;

    [numdefaults setValue:num forKey:[NSString stringWithFormat:@"%ld",(long)status]] ;
}

#pragma mark - 无数据时图片
- (void)nullArraywithStatus:(NSInteger)status
{
    nullView = [[UIView alloc] initWithFrame:CGRectMake(0, 51, __kScreenWidth, self.view.frame.size.height - 110)] ;
    nullView.backgroundColor = [UIColor whiteColor] ;
    [self.view addSubview:nullView] ;
    
    UIImageView *pageLoadingImageView = [[UIImageView alloc] initWithFrame:CGRectMake(__kScreenWidth / 4, (nullView.frame.size.height - __kScreenWidth/2) / 3, __kScreenWidth / 2, __kScreenWidth / 2)] ;
    [pageLoadingImageView setImage:[UIImage imageNamed:@"page_loading_szn_green_icon.png"]] ;
    [nullView addSubview:pageLoadingImageView] ;
    
    UILabel *label = [[UILabel alloc] init] ;
    label.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:18.0f] ;
    label.backgroundColor = [UIColor clearColor] ;
    label.textAlignment = NSTextAlignmentCenter ;
    label.textColor = [UIColor grayColor] ;
    label.frame = CGRectMake(0, pageLoadingImageView.frame.origin.y + pageLoadingImageView.frame.size.height + 10, __kScreenWidth, 20.0f) ;
    label.text = @"哎呀，暂时没有任何内容哦！" ;
    [nullView addSubview:label] ;
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    [btn setTitle:@"重新加载" forState:UIControlStateNormal] ;
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal] ;
    btn.titleLabel.font = [UIFont fontWithName:@"Arial-BoldMT" size:14.0f] ;
    [btn setBackgroundImage:[UIImage imageNamed:@"afresh_loading_btn_normal_bg.png"] forState:UIControlStateNormal] ;
    btn.frame = CGRectMake((__kScreenWidth - 80) / 2, label.frame.origin.y + label.frame.size.height + 10, 80, 30) ;
    btn.tag = status ;
    [btn addTarget:self action:@selector(btnload:) forControlEvents:UIControlEventTouchUpInside] ;
    
    [nullView addSubview:btn] ;
}

#pragma mark - 没认证状态view
- (void)creatNoRZView
{
    noRZView = [[UIView alloc] initWithFrame:self.view.frame] ;
    noRZView.backgroundColor = [UIColor whiteColor] ;
    [self.view addSubview:noRZView] ;
    UITextView *RZtextView = [[UITextView alloc] initWithFrame:CGRectMake(50, (self.view.frame.size.height - 240) / 2, __kScreenWidth - 100, 50)] ;
    RZtextView.text = @"您还尚未认证，需要认证后才能绑定服务商" ;
    RZtextView.textAlignment = NSTextAlignmentCenter ;
    RZtextView.textColor = [UIColor blackColor] ;
    RZtextView.font = [UIFont systemFontOfSize:16.0f] ;
    RZtextView.editable = NO ;
    [noRZView addSubview:RZtextView] ;
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    btn.frame = CGRectMake((__kScreenWidth - 150) / 2, RZtextView.frame.origin.y + RZtextView.frame.size.height + 10, 150, 40) ;
    [btn setBackgroundImage:[UIImage imageNamed:@"about_szn_service_protocol_normal_btn.png"] forState:UIControlStateNormal] ;
    [btn setTitle:@"申请认证" forState:UIControlStateNormal] ;
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal] ;
    [btn addTarget:self action:@selector(pushRzVC) forControlEvents:UIControlEventTouchUpInside] ;
   // btn.titleLabel.textColor = [UIColor blackColor] ;
    [noRZView addSubview:btn] ;
}



//创建label
- (UILabel *)creatlabel:(CGFloat) size color:(UIColor *)color alignment:(NSTextAlignment) alignment
{
    UILabel *label = [[UILabel alloc] init] ;
    label.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:size] ;
    label.backgroundColor = [UIColor clearColor] ;
    label.textAlignment = alignment ;
    label.textColor = color ;
    return label ;
}

#pragma mark - 左侧item点击效果

- (void)btnload:(id)sender
{
    NSInteger btnstatus = [sender tag] ;
    gdID = 0 ;
    pageNum = 0 ;
    [sheetArray removeAllObjects] ;
    [self downloadData:btnstatus] ;
}


- (void)clearbtn:(id)sender
{
//    yanzhengBtn.enabled = YES ;
//    zhuceBtn.enabled = YES ;
    [sender removeFromSuperview] ;
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    [self createNavbar] ;
    if (![touch.view isEqual:self.menu]) {
//        [self.menu dismissWithCompletion:nil];
        [self createNavbar] ;
    }
    
}


- (void)jhCustomMenu:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"点击了") ;
    NSLog(@"index:%ld",(long)indexPath.row) ;
    [self createNavbar] ;
    [undoneBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal] ;
    [havedoneBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal] ;
    [errorBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal] ;
    gdID = 0 ;
    pageNum = 0 ;
    [sheetArray removeAllObjects] ;
    switch (indexPath.row) {
        case 0:
            statusId = 4 ;
            [self downloadData:4] ;
            break;
        case 1:
            statusId = 6 ;
            [self downloadData:6] ;
            break;
        case 2:
            statusId = 7 ;
            [self downloadData:7] ;
            break;
        case 3:
            statusId = 8 ;
            [self downloadData:8] ;
            break;
        case 4:
            statusId = 9 ;
            [self downloadData:9] ;
            break;
        default:
            break;
    }
    
    
}

- (NSString *)address:(NSString *)str
{
    for (int i = 0; i < str.length; i++) {
        NSString *temp = [str substringWithRange:NSMakeRange(i, 1)] ;
        NSLog(@"temp:%@",temp) ;
        NSLog(@"i:%d",i) ;
        if ([temp isEqualToString:@"|"]) {
            str = [str substringWithRange:NSMakeRange(i+1, str.length-i-1)] ;
            NSLog(@"str:%@",str) ;
            i = -1 ;
        }
    }
    return str ;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
